Is there any difference between &a[i] and a+i, where a is int*?

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?

3 answers

  • answered 2018-04-14 15:57 Dietrich Epp

    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.

  • answered 2018-04-14 15:58 hvd

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

  • answered 2018-04-14 16:03 Pushpendra

    I think both does the same job while your program runs because the compiler will general same set of instructions for both syntax’s.

    For more information compile your program with options -save-temps . Then see the assembly instructions in .s file. If both are same then it’s just the different syntax.