为什么“a”的输出是是-80?
#include<stdio.h>
#include<conio.h>
#define ABC 20
#define XYZ 10
#define XXX ABC - XYZ
void main()
{
int a;
a = XXX * 10;
printf("\n %d \n", a);
getch();
}
我认为输出应该是 100,但是当我看到结果时,我发现输出为 -80。当我将括号设置为 #define XXX (ABC-XYZ)
时,我得到的输出为 100,但如果没有括号,我得到的输出为 -80。
#include<stdio.h>
#include<conio.h>
#define ABC 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
预处理器是一个愚蠢的野兽。它在纯粹的文本级别上工作,而不考虑它在语义上对代码所做的事情。让我们看看它在这种情况下做了什么:
becomes
成为
which 显然是
-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:
becomes
which becomes
which is, obviously,
-80
.What was probably intended was
This is one reason why macros are considered evil.
编译前将更改为以下内容:
其计算结果为
-80
will change to the following before compilation:
which evaluates to
-80
是这样计算的,
20-10*10
在宏XXX中使用大括号。
It is calculating like this ,
20-10*10
Use braces in the macro XXX.