How this code fragment work for array subscription execution direction. Please explain.
static int a[][2][3]={0,1,2,3,4,5,6,7,8,9,10,11,12};
int i=-1;
int d;
d=a[i++][++i][++i];
printf("%d",d);
How this code fragment work for array subscription execution direction. Please explain.
static int a[][2][3]={0,1,2,3,4,5,6,7,8,9,10,11,12};
int i=-1;
int d;
d=a[i++][++i][++i];
printf("%d",d);
This invokes undefined behaviour. Quoting C99 standard §6.5 ¶2
Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be read only to determine the value to be stored.
There is no sequence point in the evaluation of the array index in
d = a[i++][++i][++i];
Therefore, it's not known when the side effects of evaluation of expressions in []
will take place. Quoting C99 stanadard again §6.5.2.1 ¶2
The definition of the subscript operator [] is that E1[E2] is identical to (*((E1)+(E2))).
Therefore, the expression a[i++][++i][++i]
evaluates to
a[i++][++i][++i]
== *((a[i++][++i]) + (++i))
== *(*((a[i++]) + (++i)) + (++i))
== *(*(*(a + i++) + (++i)) + (++i))
Adding parentheses does not create a sequence point. It only defines the order of evaluation of sub-expressions of the complete expressions. It does not guarantee when the side effects of evaluating the sub-expression will take place.