+ 1
[Solved] Why is this output 27 when #define x 5+2
After this code uses #define 5 + 2, why does i = x * x * x make i = 27? https://code.sololearn.com/cty512lQ58i5/?ref=app
5 Respuestas
+ 4
The key is that x is not 7, but "5 + 2". The #define macro is a simple text replacement, meaning whenever the compiler encounters x in the source code, it is replaced by "5 + 2" (not by 7). From there on, it is simple precedence:
i = 5 + 2 * 5 + 2 * 5+ 2
i = 5 + 10 + 10 + 2
i = 27
+ 4
And this why you shouldn't use macros unless you understand how they work. It tells the compiler to replace every instance of x with 5+2, not 7.
x * x * x is replaced to
5+2*5+2*5+2
Proceed with proper operator precedence.
5+(2*5)+(2*5)+2
5+10+10+2
27
+ 2
x is 7, x*x is 17, x*x*x is 27, why though?
+ 1
It was a question in challenges, I verify the answers afterwards if I can't solve them so I can learn from my mistakes. I still don't quite understand why this happens though.. Visually it looks like 7 * 7 * 7, why does it behave this way?
+ 1
Hatsy Rei And this is why I ask, thanks for the clarification on the challenge question, I now understand :)