Multiple choice technology programming languages

What will be the output of the following program : #define swap(a,b) temp=a; a=b; b=temp; void main() { static int a=5,b=6,temp; if (a > b) swap(a,b); printf("a=%d b=%d",a,b); }

  1. a=5 b=6

  2. a=6 b=5

  3. a=6 b=0

  4. None of the above

Reveal answer Fill a bubble to check yourself
C Correct answer
Explanation

The swap macro expands to multiple statements separated by semicolons, not a single compound statement. Without braces, only 'temp=a' executes conditionally. Since 5 > 6 is false, the entire block is skipped. temp is static and initialized to 0 by default. printf outputs 'a=6 b=0' because 'a=b; b=temp;' execute unconditionally after the if block.

AI explanation

The macro #define swap(a,b) temp=a; a=b; b=temp; is dangerous because it has embedded semicolons — when substituted into if (a > b) swap(a,b);, it expands to if (a > b) temp=a; a=b; b=temp;. The if only guards the single statement temp=a;, and a=b; / b=temp; execute unconditionally afterward, regardless of the if-condition. Here a=5, b=6, so a>b is false, meaning temp=a is skipped, so temp keeps its default static value of 0. Then unconditionally: a=b → a becomes 6, and b=temp → b becomes 0. Output: a=6 b=0, matching option 3. This is a classic C gotcha illustrating why function-like macros should always be wrapped in do{...}while(0) or braces.