In C programming, evaluate the conditional operator used with lvalues (addresses): what is the output?\n\n#include<stdio.h>\nint main()\n{\n int a=0, b=1, c=3;\n ((a)? &b : &a) = a? b : c;\n printf("%d, %d, %d\n", a, b, c);\n return 0;\n}

Difficulty: Medium

Correct Answer: 3, 1, 3

Explanation:


Introduction / Context:
This C question tests deep understanding of the conditional (ternary) operator when used with lvalues (addresses) and ordinary values. It also checks evaluation order and how pointers produced by the operator can be dereferenced to assign into a selected variable.



Given Data / Assumptions:

  • a = 0, b = 1, c = 3 at program start.
  • The expression uses both a conditional that yields an address and a conditional that yields a value.
  • printf prints a, b, c in that order.


Concept / Approach:
The conditional operator has the form cond ? expr1 : expr2. If cond is nonzero (true), expr1 is evaluated and chosen; otherwise expr2 is chosen. When both expr1 and expr2 are pointers to the same effective type, the result is a pointer (an lvalue context can be created by dereferencing). Here the left-hand side is ((a) ? &b : &a), which chooses an address to write to; the right-hand side is a ? b : c, which chooses a numeric value to assign.



Step-by-Step Solution:
Evaluate condition a: a == 0 → false.Left-hand side picks &a (because a is false). Thus LHS is *(&a) which aliases variable a.Right-hand side a ? b : c → since a is false, choose c → value 3.Assignment executes: a = 3. Variables now: a=3, b=1, c=3.printf prints: 3, 1, 3.


Verification / Alternative check:
Replace a with 1 initially and mentally re-run: LHS would choose &b and RHS would choose b, assigning b=b (no change). This contrast confirms the logic.



Why Other Options Are Wrong:
“0, 1, 3” assumes no assignment happened. “1, 2, 3” or “1, 3, 1” have unjustified changes to variables b or c.



Common Pitfalls:
Forgetting that the ternary can return an lvalue-compatible pointer; mixing up which branch is selected; assuming both branches evaluate (they do not).



Final Answer:
3, 1, 3

More Questions from Control Instructions

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion