doubt in c code | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

doubt in c code

#include <stdio.h> #define sqr(x) x*x int main() { int x = 16/sqr(4); printf("%d", x); //x=16 int y=sqr(4); // y=16 return 0; } But here still the result is 16. Anyone can usually evaluate it to be as 16/16=1. What process actually going on here. Is there any difference between #define sqr(x) x*x and #define sqr(x) (x*x)

25th May 2020, 5:02 PM
Dhananjay Satish Kupekar
Dhananjay Satish Kupekar - avatar
3 Answers
+ 3
the first sqr() macro has no parentheses around the expression x * x so division happens before multiplication. 16 / sqr(4) = (16 / 4) * 4 = 4 * 4 = 16 parentheses force the multiplication to happen first. with sqr(x) (x * x) you get 16 / (4 * 4) where result is 1 as you expected. Parentheses should always be used in macros because they guarantee right evaluation order. there is also sqr((x) * (x)) which guarantees evaluation is correct when the argument itself is an expression like sqr(5 - 3).
25th May 2020, 5:26 PM
Gen2oo
Gen2oo - avatar
+ 2
Compiler first replaces sqr(x) with x*x and then you get 16/x*x at runtime which is calculated like this: 16/4*4= 4*4= 16
25th May 2020, 5:38 PM
Uros Zivkovic
Uros Zivkovic - avatar
+ 1
I think sqr(4) is the same as 4*4 that is why you got the same result for both x and y
25th May 2020, 5:04 PM
Isaac Duah [Active!]
Isaac Duah [Active!] - avatar