C程序输出
#include<stdio.h>
#define a(x) (x * x)
int main()
{
int i = 3, j;
j = a(i + 1);
printf("%d", j);
return 0;
}
我想知道为什么程序没有给出输出 16
。 (我得到输出7
。)
我非常理解这一点,但是如果程序是这样的:
#include<stdio.h>
#define a(x) (x * x)
int main()
{
int i = 3, j, k;
j = a(i++);
k = a(++i);
printf("%d\n%d", j, k);
return 0;
}
那么为什么上面的程序给出以下输出:
9
49
#include<stdio.h>
#define a(x) (x * x)
int main()
{
int i = 3, j;
j = a(i + 1);
printf("%d", j);
return 0;
}
I want to know why the program is not giving the output 16
. (I'm getting the output 7
.)
I understood the point very much but if the program is like this:
#include<stdio.h>
#define a(x) (x * x)
int main()
{
int i = 3, j, k;
j = a(i++);
k = a(++i);
printf("%d\n%d", j, k);
return 0;
}
Then why does the above program give the following output:
9
49
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
因为你做了一个糟糕的宏:
扩展到
which相当于
或
使用括号:
然后你会得到它扩展到
which做你想要的。
Because you made a bad macro:
expands to
which is equivalent to
or
Use parenthesis:
And then you'll get it to expand to
which does what you want.
阅读 C 运算符优先级并思考在这种情况下宏
a
扩展为什么。Read up on C operator precedence and think about what the macro
a
expands to in this case.预处理后,该行将
是:
当计算
i=3
时,将给出j=7
:要获得所需的结果,您需要将宏定义为:
其结果是:
当
i=3
时给出结果16
After preprocessing the line
will be:
which when evaluated for
i=3
will givej=7
:To get the desired result you need to define the macro as:
which results in:
and gives the result
16
wheni=3
因为
a(i+1)
被预处理为(i+1*i+1)
。3+3+1 = 7。
您可能需要在
x
两边使用括号。编辑:哇,这是多余的还是什么。 :/
Because
a(i+1)
gets preprocessed into(i+1*i+1)
.And 3+3+1 = 7.
You might want to use parenthesis around
x
.edit: Wow, is this redundant or what. :/
另一篇解释文章位于 http://en.wikipedia.org/wiki/C_preprocessor #优先级
Another write-up for the explanation is at http://en.wikipedia.org/wiki/C_preprocessor#Precedence
因为你的宏错了。显然它有效,但错误更微妙(不完全是,但仍然),因为扩展的代码存在一些问题,不遵循预期的操作顺序。
j = a(i+1)
将扩展为j = i + 1 * i + 1
,即7
。如果您想解决您的问题,请将您的宏重新定义为:
很高兴您现在就遇到了这个问题,而不是以后。这些类型的错误有时很难调试,但现在您将知道如何编写“专业”宏:)。
Because your macro is wrong. Apparently it works, but the error is more subtle (not quite, but still), as the expanded code has some issues, by not following the expected order of operations.
j = a(i+1)
will expand toj = i + 1 * i + 1
which is7
.If you want to resolve your problem redefine your macro as:
It's good that you've encountered this problem now, and not later. Those type of errors, are sometimes very hard to debug, but now you'll know how to write "professional" macros :).
因为 a(i+1) 被预处理为 (i+1*i+1)。
3+3+1 = 7。
您可能需要在 x 两边使用括号。
编辑:哇,这是多余的还是什么。 :/
链接|标志
Because a(i+1) gets preprocessed into (i+1*i+1).
And 3+3+1 = 7.
You might want to use parenthesis around x.
edit: Wow, is this redundant or what. :/
link|flag