C#定义宏
这是我所拥有的,我想知道它是如何工作的以及它实际的作用。
#define NUM 5
#define FTIMES(x)(x*5)
int main(void) {
int j = 1;
printf("%d %d\n", FTIMES(j+5), FTIMES((j+5)));
}
它产生两个整数:26 和 30。
它是如何做到的?
Here is what i have and I wonder how this works and what it actually does.
#define NUM 5
#define FTIMES(x)(x*5)
int main(void) {
int j = 1;
printf("%d %d\n", FTIMES(j+5), FTIMES((j+5)));
}
It produces two integers: 26 and 30.
How does it do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
发生这种情况的原因是因为您的宏将打印扩展为:
含义:
The reason this happens is because your macro expands the print to:
Meaning:
由于尚未提及,解决此问题的方法是执行以下操作:
宏扩展中
x
周围的括号可防止运算符结合性问题。Since it hasn't been mentioned yet, the way to fix this problem is to do the following:
The parentheses around
x
in the macro expansion prevent the operator associativity problem.定义只是一个字符串替换。
之后问题的答案是运算顺序:
FTIMES(j+5) = 1+5*5 = 26
FTIMES((j+5)) = (1+5)*5 = 30
define is just a string substitution.
The answer to your question after that is order of operations:
FTIMES(j+5) = 1+5*5 = 26
FTIMES((j+5)) = (1+5)*5 = 30
编译器预处理只需在看到 FTIMES 的地方进行替换,然后编译代码。 所以实际上,编译器看到的代码是这样的:
然后,考虑到运算符的偏好,你就可以明白为什么会得到 26 和 30。
The compiler pre-process simply does a substitution of FTIMES wherever it sees it, and then compiles the code. So in reality, the code that the compiler sees is this:
Then, taking operator preference into account, you can see why you get 26 and 30.
如果你想修复它:
And if you want to fix it:
预处理器将代码中出现的所有 NUM 次替换为 5,并将所有 FTIMES(x) 替换为 x * 5。然后编译器编译该代码。
它只是文本替换。
the preprocessor substitutes all NUM ocurrences in the code with 5, and all the FTIMES(x) with x * 5. The compiler then compiles the code.
Its just text substitution.
操作顺序。
FTIMES(j+5) 其中 j=1 计算结果为:
1+5*5
即:
25+1
=26
通过创建 FTIMES((j+5)),您已将其更改为:
(1+5)*5
6*5
30
Order of operations.
FTIMES(j+5) where j=1 evaluates to:
1+5*5
Which is:
25+1
=26
By making FTIMES((j+5)) you've changed it to:
(1+5)*5
6*5
30