What is the output of the following C++ program?
#include <iostream>
using namespace std;
int main() {
int a = 10, b = 20;
cout << (a > b ? a++ : --b);
cout << " " << a << " " << b;
return 0;
}
Explanation
The correct option is (b) 19 10 19.
Detailed Solution
This problem tests the evaluation of the ternary conditional operator (? :) combined with a pre-decrement operator (--b).
Step 1: Variables Initialization
Two integer variables a and b are declared and assigned values:
a=10
b=20
Step 2: Evaluating the Ternary Expression
The conditional expression is written as:
Condition?Expression 1:Expression 2
Looking at the code: (a > b ? a++ : --b)
Check Condition (a > b): Substituting the values, we check if 10 > 20. This condition evaluates to False.
Execute False Block: Since the condition is false, only Expression 2 (--b) is executed. The true block (a++) is completely ignored and not evaluated.
Step 3: Calculating --b
The operation --b is a pre-decrement operation.
It decrements the value of b by 1 immediately before it is used in the expression.
b=20−1=19
The expression returns this updated value (19), which is then printed by the first cout.
Current Console Output: 19
Step 4: Final Output Line
The next line of code prints the remaining values separated by spaces:
C++
cout << " " << a << " " << b;
Value of a: Since the condition was false, a++ never ran. Thus, a remains unchanged:
a=10
Value of b: Due to the pre-decrement step, b is now:
b=19
Combining everything printed to the console:
Output=19 10 19