C语言 是否需要括号来从指向结构的指针获取结构成员的地址,如“&(s->var)”与“&s->var”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5767973/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 08:28:51  来源:igfitidea点击:

Are parenthesis needed to get the address of a struct member from a pointer to the struct as in "&(s->var)" vs "&s->var"?

c

提问by joker

I have a struct str *s;

我有一个struct str *s;

Let varbe a variable in s. Is &s->varequal to &(s->var)?

var成为 中的一个变量s。是&s->var等于&(s->var)

回答by In silico

Behavior-wise, yes they are equivalent since the member access ->operator has a higher precedence than the address-of &operator.

行为方面,是的,它们是等效的,因为成员访问->运算符的优先级高于地址&运算符

Readibility-wise, the second one &(s->var)is much more readable than &s->varand should be preferred over the first form. With the second form, &(s->var), you won't have to second-guess what it's actually doing as you know the expression in the parentheses are always evaluated first. When in doubt, use parentheses.

&(s->var)可读性方面,第二种&s->var形式比第一种形式更具可读性,并且应该优先于第一种形式。使用第二种形式 ,&(s->var)您不必再猜测它实际在做什么,因为您知道括号中的表达式总是首先计算。如有疑问,请使用括号。

回答by Smokey.Canoe

Yes.

是的。

(-> is higher precedence than &. See http://cppreference.com/wiki/language/operator_precedence)

(-> 的优先级高于 &。参见http://cppreference.com/wiki/language/operator_precedence

回答by Christo

Yes, because the pointer dereference operator ->has higher precedence than the address operator &.

是的,因为指针解引用运算符的->优先级高于地址运算符&