1

So I have been having this rather 'unyielding' problem with a macro call in my C program. The macro I used was :

#define MACRO(X) X*X

And the problem is when I do this

printf("%d",MACRO(3));

it displays 9 as a result (which is correct). Only when I pass 3 as 2+1 as follows :

printf("%d",MACRO(2+1));

It strangely displays an outcome of 5. Can anyone please have me informed why?

  • 3
    `MACRO(2+1)` expand to `2+1*2+1`, you need `( )` – BLUEPIXY Jan 15 '16 at 21:49
  • 1
    2+1*2+1 = 2 + (1 * 2) + 1 = 5 – bruceg Jan 15 '16 at 21:49
  • @BLUEPIXY - your comments are very much worth an answer.. – artm Jan 15 '16 at 21:50
  • 2
    Seems like a dupe of [The need for parentheses in macros in C](http://stackoverflow.com/q/10820340/1281433), which uses the macro `#define SQR(x) (x*x)`, I already VTC'ed as a typo, but this would be a better dupe target. – Joshua Taylor Jan 15 '16 at 21:51
  • please remember that a macro results in a direct replace of text. To get the right operation, surround each 'x' element in the body of the macro with parens, just as you would if writing the body of the macro at the location where the macro is invoked. – user3629249 Jan 16 '16 at 13:59

2 Answers2

5
printf("%d",MACRO(2+1));

After preprocessing it will be become

printf("%d",2+1*2+1);

Since multiplication has high precidenece over addition, it will print 5;

To resolve the issue you have to define your macro as follows

#define MACRO(X) (X)*(X)
Steephen
  • 14,645
  • 7
  • 40
  • 47
4

You need to define your macro like so

#define MACRO(X) (X)*(X)

A macro is just a text expansion, so your following code is being interpreted like this...

printf("%d", 2+1*2+1);

And following order of operations you can see how you get 5 as your result.

Weather Vane
  • 33,872
  • 7
  • 36
  • 56
jacob
  • 4,656
  • 1
  • 23
  • 32