在 C 中定义类似函数的宏时,使用 {} 对或 () 对有什么区别吗?
例如:
#define FOO(x) (printf(x))
和
#define FOO(x) {printf(x)}
似乎两者都可以用于预处理,但哪个更好?
For example:
#define FOO(x) (printf(x))
and
#define FOO(x) {printf(x)}
It seems that both are viable for preprocessing, but which is better?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您将宏视为表达式,请使用
()
形式。如果您将其视为命令(并且从不作为表达式),则使用
{}
形式。或者更确切地说,使用do{}while(0)
形式,因为当在if
等关键字附近使用时,替换风险更少:If you're treating the macro as an expression, use the
()
form.If you're treating it as a command (and never as an expression) then use the
{}
form. Or rather, use thedo{}while(0)
form as that has fewer substitution hazards when used near keywords likeif
:括号
()
用于强制执行正确的计算,无论运算符优先级如何,这样您在宏扩展时就不会产生任何令人讨厌的副作用。大括号
{}
用于使宏成为 C 块语句,尽管执行此操作的规范方法是:请注意,gcc 提供了对 C 语言的扩展,使得可以从block - 如果该块用作表达式的一部分,则最后计算的表达式将是返回的值。
Parentheses
()
are used to enforce correct evaluation regardless of operator precedence, so that you hopefully won't get any nasty side effects when the macro is expanded.Braces
{}
are used to make the macro a C block statement, although the canonical way to do this is:Note that gcc provides an extension to the C language which makes it possible to return a value from a block - the last expression evaluated will be the value returned if the block is used as part of an expression.
在宏中使用括号的目的是在宏扩展时控制优先级。考虑一下:
如果像这样使用宏,
我们可能希望答案为 9,但是我们展开后得到的是:
给我们 7。为了避免这种情况,我们应该将宏编写为:
如果优先级不是一个问题,任何一种类型的括号都不是绝对必需的,尽管根据 ,macros 语义可能需要大括号 - 例如,如果您想创建一个局部变量,
The purpose of using parens in a macro is to control precedence when the macro is expanded. Consider:
if the macro is used like this
we would presumably like the answer to be 9, but what we get on expansion is:
giving us 7. To avoid this kind of thing, we should have written the macro as:
If precedence is not an issue, brackets either type are not absolutely required, though braces may be needed depending on the ,macros semantics - if for example you want to create a local variable,
如果您需要在表达式中使用
FOO(x)
,则不能使用{}
形式。例如:或
If you will ever need
FOO(x)
inside an expression, then you cannot use the{}
form. For example:or