Reputation: 37
#include <stdio.h>
#define M(x) x - x
int main () {
printf ("%d %d\n",M(M (1+2)) , M(M (3)));
return 0;
}
Can someone explain to me step by step how the result to this is 6 -6
?
Upvotes: 1
Views: 695
Reputation: 7490
What has to be clear in order to understand what's going on is that when macros are resolved it is just a replacement, not a calculation.
For example
M(1+2)
is substituted with
1 + 2 - 1 + 2
^ ^ ^
x - x
It is important to observe that the minus is not applied to the full expression. So in this case the result would be 4
.
Let's analyze our composed macros:
/* First step */
M(M(1+2) M(M(3))
M(1 + 2 - 1 + 2) M(3 - 3)
^ ^ ^ ^ ^ ^
x - x x - x
/* Second step */
M(1 + 2 - 1 + 2) M(3 - 3)
1 + 2 - 1 + 2 - 1 + 2 - 1 + 2 3 - 3 - 3 - 3
^ ^ ^ ^ ^ ^
x - x x - x
These strange sums are passed to the compiler that finally simplifies them. And the results are actually 6
(on the left) and -6
(on the right).
I guess that this result puzzled you because, with a define x-x
, you expected to get 0 for each value of x. As I showed you, the reason why you didn't get it is that the minus sign applies only to the first addend. In order to get the "always zero macro", just use parenthesis:
#define M(x) (x)-(x)
Upvotes: 2
Reputation: 224082
M(1+2)
is replaced with 1+2 -1+2
.
M(1+2 -1+2)
is replaced with 1+2 -1+2 - 1+2 -1+2
.
This is 1+2-1+2-1+2-1+2
, which is evaluated:
3-1+2-1+2-1+2
2+2-1+2-1+2
4-1+2-1+2
3+2-1+2
5-1+2
4+2
6
I expect this gives you the knowledge to figure out M(M(3))
.
Upvotes: 1