0

Why is the following program print -7 instead of throwing syntax error?
Code:

#include <stdio.h>

int main (int argc , char **argv)
{
    int arr[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
    int *b = arr + 6;
    printf("%d\n", -1[b]);
    return 0;
}
philant
  • 34,748
  • 11
  • 69
  • 112
daisy
  • 22,498
  • 29
  • 129
  • 265

1 Answers1

2

Because the index operator a[b] is just syntactic sugar, that literally translates into *(a+b) thus invoking pointer arithmetic which is commutative on its arguments. Hence it's perfectly allowed to swap the "inside" and the "outside" of …[…].

datenwolf
  • 159,371
  • 13
  • 185
  • 298
  • 2
    @Cosinus `(void*)a + ...` makes no sense. And in C it's true that `pointer_value + integer_value` gives the same as `integer_value + pointer_value` – Support Ukraine Jun 21 '21 at 07:03
  • 1
    @Cosinus: But this (what you've been suggesting) is *not* what the `index` does! The C specification (6.5.2.1 Array subscripting) literally states *"The definition of the subscript operator `[]` is that `E1[E2]` is identical to `(*((E1)+(E2)))`." (sic)* – Please read the spec (and then maybe delete your misleading comment). – datenwolf Jun 21 '21 at 14:05