What will the following C statement print? printf("%d", 10 ? 0 ? 5 : 1 : 12);
2010
What will the following C statement print?
printf("%d", 10 ? 0 ? 5 : 1 : 12);Answer: D. 1 — Concept: In C, the conditional operator condition ? expression_if_true : expression_if_false treats zero as false and any nonzero value as true. Only the…
- A.
10
- B.
0
- C.
12
- D.
1
Attempted by 117 students.
Show answer & explanation
Correct answer: D
Concept: In C, the conditional operator condition ? expression_if_true : expression_if_false treats zero as false and any nonzero value as true.
Only the selected branch is evaluated. Nested conditional operators group according to C grammar; the middle operand after ? can itself be another conditional expression.
Application: Evaluate the nested conditions from the branch selected by the outer condition.
Rewrite the statement with standard spacing: printf("%d", 10 ? 0 ? 5 : 1 : 12);
The outer condition is 10. Because 10 is nonzero, evaluate the middle expression 0 ? 5 : 1; the outer false branch 12 is not selected.
The inner condition is 0, so it selects its false expression, 1; the value 5 is not selected.
Therefore printf receives the integer 1 for the %d conversion and prints 1.
Cross-check: Explicit parentheses give printf("%d", 10 ? (0 ? 5 : 1) : 12). The inner expression evaluates to 1, and the nonzero outer condition selects it.
Result: The statement prints 1.