Reputation: 23
I just curious why the output is 4 instead of 6 . Any of you can help explain their proccess?
#include <stdio.h>
#define AMT1 a+a+a
#define AMT2 AMT1 - AMT1
main()
{
int a=1;
printf (“Amount is %d\n”,AMT2);
}
Thanks
Upvotes: 2
Views: 59
Reputation: 38724
AMT2 = AMT1 - AMT1
AMT2 = a+a+a - a+a+a
AMT2 = 1+1+1 - 1+1+1
AMT2 = 3 - 1 + 1 + 1
AMT2 = 2 + 1 + 1
AMT2 = 3 + 1
AMT2 = 4
The first rule of macros is: you need parentheses around everything. You want:
#define AMT2 (AMT1) - (AMT1)
Upvotes: 1
Reputation: 1005
a simple
AMT2 (AMT1) - (AMT1)
and/or
AMT1 (a+a+a)
should do your work.
Upvotes: 0
Reputation: 782509
After you do the macro replacements, the code becomes
printf("Amount is %d\n", 1 + 1 + 1 - 1 + 1 + 1);
Addition and subtraction are left-associative, so the expression is equivalent to
((((1 + 1) + 1) - 1) + 1) + 1)
If you want the macros to act more like variables, you need to wrap the expansions in parentheses:
#define AMT1 (a+a+a)
#define AMT2 (AMT1 - AMT1)
Upvotes: 0
Reputation: 694
Macros like this do literal text replacement. When you compile your code, AMT2
is literally being replaced by AMT1
, so you're effectively running:
printf (“Amount is %d\n”,a+a+a - a+a+a);
You can verify this yourself by looking at the output of the preprocessor (after the macros have been replaced) by running
gcc file.c -E
To solve your problem, you can either:
So your code would look like:
#include <stdio.h>
#define AMT1 (a+a+a)
#define AMT2 (AMT1 - AMT1)
int main() {
int a = 1;
printf ("Amount is %d\n", AMT2);
}
Upvotes: 1