C++执行宏观时没有得到预期的结果
#include <stdio.h>
#define swapOut(a,b) a+b-a, a+b-b
int main()
{
int a = 5;
int b = 6;
printf("%d,%d", swapOut(a+b,b-a));
return 0;
}
执行此程序时,我希望输出为“ 1,11”,但实际输出为“ 13,1”。有人可以解释这里发生了什么吗?
#include <stdio.h>
#define swapOut(a,b) a+b-a, a+b-b
int main()
{
int a = 5;
int b = 6;
printf("%d,%d", swapOut(a+b,b-a));
return 0;
}
When executing this program, I am expecting the output to be "1,11", but the actual output is "13,1". Can someone explain what is happening here ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
要了解正在发生的事情,您必须意识到宏不像功能。他们执行非常简单的文字替代。因此,当您定义
并将其用作
交换(A+B,BA)
时,将其扩展为a+b+b+ba-a+b,a+b+baba 。使用值
a = 5
和b = 6
这在13,1
中导致。因此,这是一个有价值的教训:始终用括号中的宏中围绕宏的论点。您程序的更正版本是
您预期的,这确实是输出
1,11
。To understand what's happening, you have to realise that macros are not like functions; they perform very simple text substitution. Thus, when you define
and then use it as
swapOut(a+b,b-a)
, it is expanded asa+b+b-a-a+b, a+b+b-a-b-a
. With the valuesa=5
andb=6
this results in13,1
.So here's a valuable lesson: always surround the arguments in macros with parentheses. The corrected version of your program is
This indeed outputs
1,11
as you expected.为了实现这一目标,您必须先定位该值。
To achieve this, you have to localize the value first.