+ 2

Why am I getting output as -41. Assume all header files are there?

#define multiply(x) (x*x) int c=multiply(4-9); cout<<c;

22nd Feb 2017, 9:29 AM
Soutik
Soutik - avatar
1 ответ
+ 2
This is because the preprocessor just does a literal substitution. So int c=multiply(4-9); is just substituted (during pre-processing stage) with: int c=(4-9*4-9); Because of algebraic rules of precedence the multiplication is calculated first: int c=(4-36-9); The answer is then -41. If you want that to work correctly you can do this: #define multiply(x) ((x)*(x)) BTW, if you turn your preprocessor function into a normal function it would work correctly: int multiply(int x){return x*x;} The reason it works here is because the expression is resolved first, and then the result of the expression is passed as argument to the function. So the x*x step in the normal function would be doing -5*-5, whilst the preprocessor version is doing (4-9)*(4-9).
22nd Feb 2017, 10:44 AM
Ettienne Gilbert
Ettienne Gilbert - avatar