Macro pitfalls: what does this program print? #include<stdio.h> #define SQR(x) (xx) int main() { int a, b = 3; a = SQR(b+2); // expands to (b+2b+2) printf("%d ", a); return 0; } Assume usual C operator precedence.

Difficulty: Medium

Correct Answer: 11

Explanation:

Introduction / Context:This checks macro-expansion understanding and the importance of parenthesizing macro parameters. Using expressions as macro arguments can lead to surprising results when operator precedence interacts with the expanded text.

Given Data / Assumptions:

  • Macro SQR(x) is defined as (xx).
  • We call SQR(b+2) with b = 3.
  • C operators: multiplication has higher precedence than addition.

Concept / Approach:Textual macro expansion replaces x with b+2, so SQR(b+2) becomes (b+2b+2). The multiplications bind first, changing the intended meaning from (b+2)(b+2) to b + 2b + 2.

Step-by-Step Solution:Expand: SQR(b+2) → (b+2b+2).Evaluate with b = 3: 3 + 23 + 2 = 3 + 6 + 2 = 11.Assign to a and print → 11.

Verification / Alternative check:Defining #define SQR(x) ((x)(x)) would evaluate SQR(b+2) as (55) = 25, the intended square.

Why Other Options Are Wrong:25 would require fully parenthesized macro arguments.Error / Garbage value: the code compiles and runs deterministically.

Common Pitfalls:Forgetting to parenthesize macro parameters and the entire replacement; relying on macros with side effects.

Final Answer:11

More Questions from C Preprocessor

Discussion & Comments

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