Why this code outputs "9 7", but not "9 16"??? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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; }

8th Mar 2019, 9:42 AM
Hugo H
Hugo H - avatar
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))
8th Mar 2019, 10:03 AM
Prokopios Poulimenos
Prokopios Poulimenos - avatar
+ 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
8th Mar 2019, 10:05 AM
Anna
Anna - avatar