可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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).