是否有一个很好的理由总是封闭在括号在C界定? [英] Is there a good reason for always enclosing a define in parentheses in C?

查看:148
本文介绍了是否有一个很好的理由总是封闭在括号在C界定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

显然,有次,其中定义取值必须有括号,就像这样:

Clearly, there are times where defines must have parentheses, like so:

#define WIDTH 80+20

int a = WIDTH * 2; //expect a==200 but a==120

所以我一直括号,即使它只是一个数字:

So I have always parenthesized, even if it's just a single number:

#define WIDTH (100)

有人新的 C 问我为什么这样做,所以我试图找到一个边缘情况在一个号码没有括号定义引起的问题,但我不能想到一个。

Someone new to C asked me why I do this, so I tried to find an edge case where the absence of parentheses on a single number define causes issues, but I can't think of one.

请问这种情况是否存在?

Does such a case exist?

推荐答案

。在preprocessor连接符( ## )会导致一些问题,例如:

Yes. The preprocessor concatenation operator (##) will cause issues, for example:

#define _add_penguin(a) penguin ## a
#define add_penguin(a) _add_penguin(a)

#define WIDTH (100)
#define HEIGHT 200    

add_penguin(HEIGHT) // expands to penguin200
add_penguin(WIDTH)  // error, cannot concatenate penguin and (100) 

有关stringization一样的()。显然,这是一个极端例子,也许并不重要考虑如何宽度将presumably使用。尽管如此,它是值得记住的关于preprocessor。

Same for stringization (#). Clearly this is a corner case and probably doesn't matter considering how WIDTH will presumably be used. Still, it is something to keep in mind about the preprocessor.

(为什么加入第二企鹅失败的原因是的preprocessing规则C99微妙的细节 - IIRC 的,因为串联两个非占位符preprocessing标记必须总是失败导致单个preprocessing令牌 - !不过这是无关紧要的,即使串联允许它仍然会给不同的结果比加括号的#define

(The reason why adding the second penguin fails is a subtle detail of the preprocessing rules in C99 - iirc it fails because concatenating to two non-placeholder preprocessing tokens must always result in a single preprocessing token - but this is irrelevant, even if the concatenation was allowed it would still give a different result than the unbracketed #define!).

所有其它的响应是正确的仅仅在于,由于事实上,一个数字是原子不会从来看C ++的扫描仪的点重要。不过,我的问题阅读,没有只,没有进一步的preprocessor扩张的情况下,应考虑的星座,所以其他的反应是,即使我完全同意的意见同意其内所载的错。

All other responses are correct only insofar that it doesn't matter from the point of view of the C++ scanner because, indeed, a number is atomic. However, to my reading of the question there is no sign that only cases with no further preprocessor expansion should be considered, so the other responses are, even though I totally agree with the advice contained therein, wrong.

这篇关于是否有一个很好的理由总是封闭在括号在C界定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆