0
What is the output of below code and why?
#include <stdio.h> #define square(x) x*x int main() { printf("%d",square(4-1)); return 0; }
4 Answers
+ 4
The code in question (found in OP's profile)
https://code.sololearn.com/chDFYl81R58B/?ref=app
* Output:
-1 (minus one)
* Explanation:
Every macro calls will be replaced with the macro body definition "as-is". In that code, you define "x*x" as the macro body, but it yields unexpected output, because the compiler calculates <x> [which is an expression -> (4-1)] differently than what you think, instead of doing (4-1)*(4-1) it simply does 4-1*4-1, taking into account the operator precedence, that is 4-(1*4)-1, or 4-4-1, which yields -1.
To prevent such things from happening wrap the macro argument within parentheses, as follows:
#define square(x) (x)*(x)
This will ensure argument <x> (which was passed in as an expression rather than a value) is calculated before it is multiplied by itself. Hence it will be calculated as (4-1)*(4-1), and you'll have the right result : )
Hth, cmiiw
+ 2
FYI - If you put the URL in the tags area, we can't click on it or copy the text.
For the benefit of others looking in on this thread:
https://code.sololearn.com/chdfyl81r58b/?ref=app
+ 2
square(4-1) => 4-1*4-1 => 4-4-1 => -1
Macro are expanded with simple substitution
0
4-1*4-1->4-4+1+->-1