括号围绕常数或铸造表达式周围涉及常数
我不时看到此代码:
#define X1 (13)
#define X2 ((size_t)13)
据我了解,(外)()
在这里是多余的。那是对的吗?
UPD:某些软件开发指南可能需要它。
例如: Misra C:2004年,规则19.4(要求):
c宏只能扩展到支撑的初始评估器,常数,括号的表达式,类型的限定符,存储类规范符或do-while-while-while-while-while-while-while-while-while-while-while-while-while-while-while-while-while-while-while-while-per构建体。
但是,Misra C:2012有:
#define MY_NULL_2 ( void * ) 0
#define sqrt( x ) ( _BUILTIN_sqrt ( x ) )
From time to time I see this code:
#define X1 (13)
#define X2 ((size_t)13)
As I understand, the (outer) ()
are redundant here. Is that correct?
UPD: Some software development guidelines may require it.
For example:
MISRA C:2004, Rule 19.4 (required):
C macros shall only expand to a braced initialiser, a constant, a parenthesised expression, a type qualifier, a storage class specifier, or a do-while-zero construct.
However, MISRA C:2012 has:
#define MY_NULL_2 ( void * ) 0
#define sqrt( x ) ( _BUILTIN_sqrt ( x ) )
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不认为第一个例子需要括号,但始终括号宏观的宏观是一个合理的习惯。
如果您从定义中删除外括号,然后在上下文
x2 [a]
中调用它,则第二个将产生意外的分组。I don't believe the first example needs parentheses, but always parenthesizing macro bodies is a reasonable habit.
The second one will produce unexpected grouping if you remove the outer parentheses from the definition and then invoke it in the context
X2[a]
.在第一种情况下,
(13)
可能会引起问题。参见下文。在第二种情况下
((size_t)13)
倾向于防止问题,因为它可以确保铸件(没有顶部优先顺序)仅应用于13
,而不是以下代码。()
在#define x1(13)
有缺点。考虑弦乐。作为
(80)
,形成了错误的格式字符串。输出
In the first case,
(13)
can cause a problem. See below.In the the 2nd case
((size_t)13)
tends to prevent problems as it insures the cast (which does not have top order of precedence) is applied to only13
and not some following code.The
()
in#define X1 (13)
have a disadvantage. Consider stringification.As
(80)
, the incorrect format string is formed.Output