ProgrammingHardTCS NQT · Infosys pattern

What is printed?

What is printed?
int a = 5;
int b = 10;
int result = a > b ? a : b > 0 ? b : 0;
printf("%d", result);
  1. A. 0
  2. B. 5
  3. C. Compile-time error: nested ternary needs explicit parentheses
  4. D. 10

Correct answer: D. 10

The ternary operator is right-associative, so a > b ? a : b > 0 ? b : 0 parses as a > b ? a : (b > 0 ? b : 0). Since a > b (5 > 10) is false, the whole expression evaluates the else-branch, b > 0 ? b : 0; since b > 0 (10 > 0) is true, that gives b, 10.

More C Programming questions

Exams that ask this topic