#include<stdio.h>
#include<conio.h>
#define ABC 开发者_StackOverflow社区20
#define XYZ 10
#define XXX ABC - XYZ
void main()
{
int a;
a = XXX * 10;
printf("\n %d \n", a);
getch();
}
I thought the output should be 100 but when I saw the result I found output as -80. When I put brackets as #define XXX (ABC-XYZ)
then I get output as 100 but without brackets I get output as -80.
The preprocessor is a dumb beast. It works on a purely textual level, without regard for what it's doing to the code semantically. Let's see what it does in this case:
a = XXX * 10;
becomes
a = ABC - XYZ * 10;
which becomes
a = 20 - 10 * 10;
which is, obviously, -80
.
What was probably intended was
#define XXX (ABC - XYZ)
This is one reason why macros are considered evil.
a = XXX * 10;
will change to the following before compilation:
a = 20 - 10 * 10;
which evaluates to -80
It is calculating like this ,
20-10*10
Use braces in the macro XXX.
#define XXX (ABC-XYZ)
Here XXX is replaced by ABC-XYZ So it is look like the follow
20 - 10 * 10
So the output is -80
精彩评论