0

Problems using define in C. Works well when I call OP(9), but when I call OP(7+2) I get 23. Why?

 #include<stdio.h>
 #include<stdlib.h>

 #define OP(x) x*x;

 int main() {
 int x,y;

 x = 2;
 y = OP(7+2);
 printf("%d", y);

 return 0;

 }

Why prints 23 and not 81?

Ryan
  • 14,392
  • 8
  • 62
  • 102
MM PP
  • 4,050
  • 9
  • 35
  • 61
  • 2
    Use parentheses. This must be a duplicate question. – jxh Feb 09 '17 at 17:39
  • 1
    Parentheses — or lack thereof. Look at `7 + 2*7 + 2` – that is `23`. If you want `(7+2)*(7+2)`, add the parentheses: `#define OP(x) ((x)*(x))` — all of them! – Jonathan Leffler Feb 09 '17 at 17:39
  • 1
    "...but when I call `OP(7+2)`..." You cannot "call" `OP(7 + 2)`. `OP` is a macro, not a function. Macros cannot be "called". They can only be substutuded/replaced. The rest follows. – AnT stands with Russia Feb 09 '17 at 17:45

1 Answers1

4

You should wrap x in parentheses in order to force precedence. However, it is also essential to wrap the entire expression in parentheses.

#define OP(x) ((x)*(x))
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Ryan
  • 14,392
  • 8
  • 62
  • 102