What is the output of the following C program? #include<stdio.h> #define…

2014

What is the output of the following C program?

#include<stdio.h>
#define SQR(x) (x*x)
int main()
{
    int a;
    int b=4;
    a=SQR(b+2);
    printf("%d\n",a);
    return 0;
}
  1. A.

    14

  2. B.

    36

  3. C.

    18

  4. D.

    20

Attempted by 1037 students.

Show answer & explanation

Correct answer: A

Concept

In C, a function-like macro performs purely TEXTUAL substitution before compilation. The preprocessor pastes the argument's raw token text into the body exactly as written — it does NOT evaluate the argument first and does NOT add any protective parentheses around it.

Application

  1. The macro is #define SQR(x) (x*x), and it is called as SQR(b+2).

  2. The preprocessor replaces every x in the body (x*x) with the literal token text b+2, giving (b+2*b+2).

  3. Now ordinary C precedence applies: multiplication binds tighter than addition, so b+2*b+2 means b + (2*b) + 2.

  4. Substituting b=4: 4 + (2*4) + 2 = 4 + 8 + 2 = 14.

Cross-check

Contrast: had the macro been defined safely as #define SQR(x) ((x)*(x)), the call would expand to ((b+2)*(b+2)) = 6*6 = 36. The missing parentheses are exactly why the output is 14 and not 36.

Explore the full course: Isro