Reputation: 53
Obviously both &a[i]
and a+i
return int*
. The question is whether they are performed in the same way, since there are two operators in &a[i]
but only one operator in a+i
?
Upvotes: 2
Views: 996
Reputation:
Historically, technically, given int a[10];
, &a[10]
used to be technically invalid because it dereferenced a pointer past the end of an array, whereas a+10
has always been valid.
Nowadays: a[i]
is defined as *(a+i)
, so &a[i]
means &*(a+i)
. When a
is an array or a pointer, and i
is an integer, then yes, that is equivalent to a+i
. When both &
and *
are applied to the same pointer expression, they are now specifically specified to have no effect.
More details for those interested in the history: this is the text that was added in C99.
6.5.3.2 Address and indirection operators
3 [...] If the operand is the result of a unary
*
operator, neither that operator nor the&
operator is evaluated and the result is as if both were omitted, except that the constraints on the operators still apply and the result is not an lvalue.
This text was not there yet in C89/C90, so the rule that a pointer subjected to the *
operator has to actually point to an object or function still technically applied. The standard was changed specifically to make such constructs valid.
Upvotes: 5
Reputation: 213358
In C, they are identical. The C standard defines a[i]
to be the same as *(a + i)
, so &a[i]
is just &*(a + i)
which is a + i
. (The surprising consequence of this is that you could just as easily write i[a]
.)
The number of operators has no real significance here.
Upvotes: 12