+ 3

Task about #define x 5+2 in C++ battle

There is following task in C++ battle. We have the code: #define x 5+2 void main() { cout x*x*x; } And there is question: what output will be? I thought that x=7 and so output is 7^3=343. But right answer is 27. Please, explain why output is 27. https://code.sololearn.com/c31k0ji5URfW/?ref=app

15th May 2018, 8:56 AM
Ivan Vladimirov
Ivan Vladimirov - avatar
5 odpowiedzi
+ 6
Multiplication has higher precedence than addition. So in your case: 5+2*5+2*5+2 evaluates to 27 thats the nasty nature of #define I would suggest using constexpr instead.
15th May 2018, 9:18 AM
Kuba H
Kuba H - avatar
+ 12
Try adding the line: cout << 5 + 2 * 5 + 2 * 5 + 2; And see what result you get.
15th May 2018, 9:09 AM
jay
jay - avatar
+ 12
Like Kuba H has said.. cout << 5 + 2 * 5 + 2 * 5 + 2; Becomes cout << 5 + 10 + 10 + 2;
15th May 2018, 9:20 AM
jay
jay - avatar
+ 7
Keep in mind that #define does not evaluate the expression it just copy paste it.
15th May 2018, 9:27 AM
Kuba H
Kuba H - avatar
+ 7
Thank you jay and Kuba H.
15th May 2018, 10:33 AM
Manual
Manual - avatar