When should we use sizeof with and without parentheses [duplicate]

匿名 (未验证) 提交于 2019-12-03 01:18:02

问题:

This question already has an answer here:

typedef struct rem{     int  addr;     char addrbuf[32]; } foo; 

Both of these codes return the same results

foo addr; printf("size is: %d\n",sizeof addr); printf("size is: %d\n",sizeof (foo)); 

size is: 36

size is: 36

But when should we use sizeof with and without parentheses?

回答1:

When using sizeof with a type, you need parentheses around the type. When using it with an expression, you don't. But you can of course include them in this case as well, and you don't have to worry about operator precedence in such case. With uncommon operators such as this one, fewer people would be sure of the precedence, so clarity certainly helps.

So I'd say it's preferable to use them always.



回答2:

[expr.sizeof]/1:

The operand is either an expression, which is an unevaluated operand (Clause 5), or a parenthesized type-id.

Thus the parentheses are required for types only. If you prefer to use parentheses for clarity and consistency (as I do) you can always use them though, as parentheses around an expression form another expression.
The operator precedence of sizeof is not very well known and could cause irritations.

Also, for the sizeof... operator, you always have to use parentheses (another reason for consistency).



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!