[Solved] Why is this output 27 when #define x 5+2 | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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

14th Sep 2018, 4:54 AM
Philip
Philip - avatar
5 Answers
+ 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
14th Sep 2018, 5:55 AM
Shadow
Shadow - avatar
+ 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
14th Sep 2018, 5:56 AM
Hatsy Rei
Hatsy Rei - avatar
+ 2
x is 7, x*x is 17, x*x*x is 27, why though?
14th Sep 2018, 5:01 AM
๐Ÿ‘‘ Prometheus ๐Ÿ‡ธ๐Ÿ‡ฌ
๐Ÿ‘‘ Prometheus ๐Ÿ‡ธ๐Ÿ‡ฌ - avatar
+ 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?
14th Sep 2018, 5:16 AM
Philip
Philip - avatar
+ 1
Hatsy Rei And this is why I ask, thanks for the clarification on the challenge question, I now understand :)
14th Sep 2018, 6:37 AM
Philip
Philip - avatar