Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is &array[i] always equivalent to (array + i)? [duplicate]

Recently, I saw a C code like this:

#include <stdio.h>

int main(void) {
    int array[5] = {1, 2, 3, 4, 5};

    for (int* ptr = &array[0]; ptr != &array[5]; ptr++)
        printf("%d\n", *ptr);

    return 0;
}

Since operator [] is prioritized over operator & in C, I think &array[5] is equivalent to &(*(array + 5)), which causes undefined behavior (we are not allowed to dereference array + 5). That is why I suspect the code above is ill-formed. (By the way, I know that ptr != array + 5 is okay.)

I tested this code using GCC 11.1.0 and Clang 12.0.0 with -O0 -fsanitize=address,undefined compiler flags, but both compilers interpreted &array[5] as array + 5, and no unexpected behavior happened.

Is &array[i] always equivalent to array + i (even when array[i] is invalid)? Thank you in advance.

like image 476
user16257574 Avatar asked Dec 18 '22 11:12

user16257574


1 Answers

Firstly there is 6.5.2.1/2:

The definition of the subscript operator [] is that E1[E2] is identical to (*((E1)+(E2)))

Then it is defined in (6.5.3.2/3) , the unary & operator:

[...] Similarly, if the operand is the result of a [] operator, neither the & operator nor the unary * that is implied by the [] is evaluated and the result is as if the & operator were removed and the [] operator were changed to a + operator.

Which is explicitly saying that &x[y] means (x) + (y) exactly.

like image 73
M.M Avatar answered Dec 31 '22 02:12

M.M