ProgrammingHardHCL · Tech Mahindra pattern

What is printed?

What is printed?
int x = 10;
int y = x > 5 ? x > 8 ? 1 : 2 : 3;
printf("%d", y);
  1. A. 3
  2. B. 2
  3. C. Compile-time error: ambiguous nested ternary
  4. D. 1

Correct answer: D. 1

Nested ternaries associate from the right: x > 5 ? (x > 8 ? 1 : 2) : 3. x > 5 (10>5) is true, so evaluate the inner ternary: x > 8 (10>8) is also true, giving 1. The outer else-branch (3) is never reached.

More C Programming questions

Exams that ask this topic