C 预处理器和操作顺序
我正在学习 C,但我不明白这一点:
#define square(x) x*x
a = square(2+3) //a = 11
运行时,为什么 a
最终会变成 11
?
I'm learning C, but I do not understand this:
#define square(x) x*x
a = square(2+3) //a = 11
When this is run, why does a
end up being 11
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
它扩展为
2+3*2+3
,相当于2+(3*2)+3
。使用括号来修复它:现在尝试使用
square(x++)
,您将遇到更多问题(未定义的行为)。如果可以的话,请避免将其作为宏来执行。It expands to
2+3*2+3
, which is equivalent to2+(3*2)+3
. Use parentheses to fix it:Now try it with
square(x++)
and you'll run into more problems (undefined behavior). Avoid doing this as a macro if you can.square(2+3)
扩展为2+3*2+3
相当于2+(3*2)+3
(*
的优先级高于+
)。在GCC中,您可以使用-E 选项来查看预处理器生成的内容:
输出:
补救措施
试试这个:
square(2+3)
expands to2+3*2+3
which is equivalent to2+(3*2)+3
(*
has higher precedence than+
).In GCC, you can use -E option to see what your preprocessor generates:
Output:
Remedy
Try this:
尝试:
Try:
由于
2 + 3
在表达式x * x
中按字面替换,因此它变为2 + 3 * 2 + 3
,并且*
运算符具有更高的优先级,因此您不会得到预期的结果。始终将宏参数和整个表达式括在括号中以避免这种情况:
另请注意,您传递的任何表达式都将被计算两次,如果表达式具有副作用(例如赋值或函数调用),则这可能是不希望的。在这些情况下,最好使用内联函数。
Because
2 + 3
is substituted literally in the expressionx * x
, it becomes2 + 3 * 2 + 3
, and the*
operator has a higher precedence so you don't get the expected result.Always enclose macro arguments and the whole expression in parentheses to avoid this:
Also note that any expression you pass will be evaluated twice, and that can be undesired if the expression has a side effect such as an assignment, or a function call. In these cases it is better to use an inline function.
想想当宏展开时你会得到什么。 C 预处理器将扩展它,因为
您需要正确定义宏。始终将宏变量括在括号内。这会给你预期的结果。
宏展开式是这样的:
Think about what you get when the macro is expanded. The C preprocessor will expand this as
You need to correctly define your macro. Always enclose the macro variable in parentheses. This would give you the expected result.
The macro expansion would be this: