0

Please explain the output — I am getting the output as 20, but it should be 64 if I am not wrong.

#include<stdio.h>
#define SQUARE(X) (X*X) 
main() 
{ 
    int a, b=6; 
    a = SQUARE(b+2); 
    printf("\n%d", a);
}
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • You are wrong — it should be 20. Run `cc -E code.c` and look at the expansion of SQUARE. – Jonathan Leffler Aug 12 '16 at 06:09
  • Incidentally, you need to be careful with magic quotes `“\n%d”` vs regular quotes `"%d\n"` — the C compiler won't accept magic quotes. You should normally end output lines with a newline rather than, or as well as, starting the line with a newline. You should use an explicit return type on `main()` — of `int` (see [What should `main()` return in C and C++?](http://stackoverflow.com/questions/204476/)). – Jonathan Leffler Aug 12 '16 at 06:14

1 Answers1

3

The correct result is 20.

Macros are simple text substitutions.

To see that the result is 20, just replace the X with b+2. Then you have:

b+2*b+2

as b is 6 it is

6+2*6+2

which is 20

When using macros it is important to use parenthesis so the macro should look

# define SQUARE(X) ((X)*(X)) 

Then the result will be 64 as the evaluation is

(b+2)*(b+2)

(6+2)*(6+2)

8*8

64
Support Ukraine
  • 42,271
  • 4
  • 38
  • 63