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)
4 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).
+ 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
+ 1
I think
sqr(4) is the same as 4*4
that is why you got the same result for both x and y