0

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);
smamran
  • 741
  • 2
  • 14
  • 20
  • 4
    This code doesn't work; your line with multiple `++` invokes undefined behaviour. See http://stackoverflow.com/questions/949433/why-are-these-constructs-undefined-behavior. – Oliver Charlesworth Apr 03 '14 at 05:12
  • This code works. gcc 4.8.1 results d = 2. – smamran Apr 03 '14 at 05:16
  • 2
    It's just bad luck that it exhibits the desired behaviour. Switch to a different compiler, version, platform, etc., and it may exhibit different behaviour. – Oliver Charlesworth Apr 03 '14 at 05:16
  • @imran_khan Read this http://blog.codinghorror.com/the-works-on-my-machine-certification-program/ – ajay Apr 03 '14 at 05:21
  • There is not even any "desired behavior" here, because in addition to the undefined behavior, the order of evaluation of those 3 sub-expressions is unspecified. So if you expect this code to behave in a certain way, you are basing your expectations on something you made up yourself, out of the blue. – Lundin Apr 03 '14 at 06:41

2 Answers2

2

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.

ajay
  • 9,402
  • 8
  • 44
  • 71
1
a[i++][++i][++i]

This statement results in undefined behaviour. you can try executing code here and you will get different output than 2 that you got. Its not that you will not get output but the behaviour is undefined so you cant predict the output.

LearningC
  • 3,182
  • 1
  • 12
  • 19