Challenge - 5 Problems
Ternary Operator Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of nested ternary operator
What is the output of this C++ code snippet?
C++
int x = 5, y = 10; int result = (x > y) ? (x - y) : ((x == y) ? 0 : (y - x)); std::cout << result << std::endl;
Attempts:
2 left
💡 Hint
Remember the ternary operator evaluates conditions from left to right.
✗ Incorrect
Since x (5) is not greater than y (10), the first condition is false. Then it checks if x == y, which is false. So it returns y - x, which is 10 - 5 = 5.
❓ Predict Output
intermediate2:00remaining
Ternary operator with side effects
What will be printed by this C++ code?
C++
int a = 3, b = 4; int c = (a > b) ? (a += 2) : (b += 3); std::cout << a << " " << b << " " << c << std::endl;
Attempts:
2 left
💡 Hint
Check which condition is true and which variable is updated.
✗ Incorrect
Since a (3) is not greater than b (4), the else part runs, so b is increased by 3 to 7, and c gets the value 7. a remains 3.
🧠 Conceptual
advanced2:00remaining
Understanding ternary operator associativity
Consider the expression: int x = 1 ? 0 : 1 ? 2 : 3;
What is the value of x after this statement?
Attempts:
2 left
💡 Hint
Ternary operators associate from right to left.
✗ Incorrect
The expression is parsed as int x = 1 ? 0 : (1 ? 2 : 3); Since 1 is true, x is assigned 0.
❓ Predict Output
advanced2:00remaining
Ternary operator with different types
What is the output of this code snippet?
C++
auto val = true ? 3.5 : 2; std::cout << typeid(val).name() << " " << val << std::endl;
Attempts:
2 left
💡 Hint
Check the type deduced by the ternary operator when operands have different types.
✗ Incorrect
The ternary operator promotes int 2 to double 2.0, so val is double (typeid name 'd') and value 3.5.
🔧 Debug
expert2:00remaining
Identify the error in ternary operator usage
Which option will cause a compilation error in this code snippet?
C++
int a = 5, b = 10; int result = (a > b) ? a : "10"; std::cout << result << std::endl;
Attempts:
2 left
💡 Hint
Check the types of the values returned by the ternary operator.
✗ Incorrect
Option D uses a string literal "10" which cannot be assigned to int result, causing a compilation error.