+ 6
Why this code outputs "9 7", but not "9 16"???
#include <stdio.h> #define sqr(i) i*i int main(){ printf("%d %d", sqr(3), sqr(3+1)); return 0; }
2 Answers
+ 7
Operator precedence. You see, because sqr is a macro, not a function, this is what the compiler actually sees: (3+1*3+1)
Use : #define sqr(i) ((i)*(i))
+ 6
Because sqr(i) will be replaced with i*i.
sqr(3+1) = 3+1*3+1 = 7
Change the definition to
#define sqr(i) (i)*(i)
sqr(3+1) = (3+1)*(3+1) = 16