+ 1
How this square function works?
Can someone explain why the result of this function is 9. #define square(x) x*x int main() { printf("%d", square(4+1)); return 0; }
3 Respostas
+ 3
In this case square(x) means that the x will be replaced by whatever you put it. It will not be processed.
Hence, what happens is the compiler treats it like 4+1*4+1, because x is treated as 4+1.
And if you know your order of operations you know the answer is 4+4+1=9.
This is a trouble with macros. To fix this, do:
#define square(x) (x)*(x)
And square(4+1) will output 5² correctly, which is 25.
+ 1
It's not doing (4+1)*(4+1) but rather 4+1*4+1 == 4 + 4 + 1 == 9.
0
Thanks for the answers and very good explanation from Prometheus.