开发者

is *(1 + &foo) the same as *(&foo + 1) in C/C++?

Is this:

*(1 + &foo)

the same as this?

*(&foo + 1)

'+' and '&' have the same precedence and they are evaluated right-to-left. However you can't interpret the second case like this:

开发者_JS百科
*(&(foo + 1))

...because you can only use '&' with an l-value (it won't even compile if you write it like that). So will it be garbage? Or will it safely figure out what you meant?


Yes, they are equivalent (the third one obviously is not).

The unary & operator has higher precedence than the binary + operator (as all unary operators do), so &foo + 1 parses as (&foo) + 1. What you are thinking of when you say they have the same precedence is the unary + operator (which is a different operator) has the same precedence as unary &.


Yes, they are the same. Note that binary + has a lower precedence than &. You're probably thinking of unary +.


As shown on the Wikipedia page, & and + only have the same precedence when interpreting + as a unary operator -- for example, as in a - +b.

When interpreting + as a binary operator, it has a lower precedence than &, and so the second case will be interpreted as *((&foo) + 1) rather than *(&(foo + 1)).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜