How this square function works? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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; }

19th Jan 2019, 6:30 AM
Jari
Jari - avatar
3 Answers
+ 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.
19th Jan 2019, 6:45 AM
👑 Prometheus 🇸🇬
👑 Prometheus 🇸🇬 - avatar
+ 1
It's not doing (4+1)*(4+1) but rather 4+1*4+1 == 4 + 4 + 1 == 9.
19th Jan 2019, 6:40 AM
Diego
Diego - avatar
0
Thanks for the answers and very good explanation from Prometheus.
19th Jan 2019, 7:22 AM
Jari
Jari - avatar