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;
}
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;
}
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 …[…]
.