msilverm
msilverm

Reputation: 93

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:

*(&(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?

Upvotes: 3

Views: 245

Answers (3)

Zooba
Zooba

Reputation: 11438

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)).

Upvotes: 1

mgiuca
mgiuca

Reputation: 21357

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 &.

Upvotes: 9

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272517

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

Upvotes: 1

Related Questions