Evaluate a simple SWAP macro with the comma operator: what is the output? #include<stdio.h> #define SWAP(a, b) int t; t = a, a = b, b = t; int main() { int a = 10, b = 12; SWAP(a, b); printf("a = %d, b = %d\n", a, b); return 0; }

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;
  • Macro expands inline inside 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 = at = 10.a = ba = 12.b = tb = 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:

No compilation/link errors arise here; 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.

More Questions from C Preprocessor

Discussion & Comments

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