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. 1Concept: In C, the conditional operator condition ? expression_if_true : expression_if_false treats zero as false and any nonzero value as true. Only the…

  1. A.

    10

  2. B.

    0

  3. C.

    12

  4. 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.

  1. Rewrite the statement with standard spacing: printf("%d", 10 ? 0 ? 5 : 1 : 12);

  2. The outer condition is 10. Because 10 is nonzero, evaluate the middle expression 0 ? 5 : 1; the outer false branch 12 is not selected.

  3. The inner condition is 0, so it selects its false expression, 1; the value 5 is not selected.

  4. 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.

Explore the full course: Tpsc Assistant Technical Officer

Loading lesson…