Why the Output is 16? | SoloLearn: Learn to code for FREE!

+2

Why the Output is 16?

I thought the output will be 1, But i've got 16. #define sqr(x) x*x int x = 16/sqr(4); printf("%d", x); Why...?

1/19/2021 7:19:14 AM

Asrar

3 Answers

New Answer

+3

#define macros aren't functions even if they look so. They actually just kind of copy and paste code. In your case the macro is preprocessed to: int x = 16/4*4; That's 16. If you want to avoid this you have to use parenthesis around your macro like this: #define sqrt(x) (x*x)

+4

Macros are raw string representation of their values. I'm not sure if this is the right way to define them but what actually is going on in your code is because the sqr macros was expanded to 4 * 4, so the variable x becomes 16/4 * 4 = 4 * 4 = 16 If you must get 1 as the result, you must make the * operator precedes over / so, the variable x should be sqr(4) / 16 Which would be translated as (4*4)/16 = 1 instead of 16/sqr(4)

+3

Mirielle and Aaron Eberhardt Thank you guys