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.