Difficulty: Easy
Correct Answer: a = 12, b = 10
Explanation:
Introduction / Context:
Here we examine how a macro that declares a temporary and uses the comma operator performs a swap. Many learners expect errors from declarations in macros, but they are legal within a statement context once expanded. The result depends on the order of evaluation implied by the comma operator sequence.
Given Data / Assumptions:
a = 10
, b = 12
.#define SWAP(a, b) int t; t = a, a = b, b = t;
main
.
Concept / Approach:
After expansion, the code becomes a declaration of t
and three simple assignments separated by commas. The comma operator evaluates left to right, discarding intermediate values, but here each sub-expression produces the side effect we want: save a
in t
, copy b
into a
, then copy t
into b
.
Step-by-Step Solution:
t = a
→ t = 10
.a = b
→ a = 12
.b = t
→ b = 10
.Prints: a = 12, b = 10
.
Verification / Alternative check:
Print a
and b
after each step; or wrap the macro in do { ... } while(0)
to make it syntactically safer in general use.
Why Other Options Are Wrong:
t
is declared and used in-scope.Other outputs contradict the swap order.
Common Pitfalls:
Not wrapping multi-statement macros; name collisions if t
already exists (a reason to prefer block scoping or typeof
tricks).
Final Answer:
a = 12, b = 10.
Discussion & Comments