3

Can someone please explain why the output of this code is 3 and not 4?

#define square(x) (x*x)

int main () {
    int x,y=1;
    x=square(y+1);
    printf("%d\n",x);
    return 0;
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770

1 Answers1

2

The reason is that what preprocessor does about macros is quite like a search-replace. So you get y+1*y+1 which gives three. To avoid such problems

  • wrap every variable in macro definition with parentheses #define square(x) ((x)*(x))
  • use functions instead (prefered as less likely to run into random errors)
user12986714
  • 741
  • 2
  • 8
  • 19