6

I had a person claiming that this line is not covered by the C++ standard:

int i(1);
array_of_int[i] = i++;

The person said that it will assign 1 but we cannot know whether it will be in array_of_int[1] or array_of_int[2] although visual studio and most of compilers will be in array_of_int[1].

Is he correct ?

Grizzly
  • 19,595
  • 4
  • 60
  • 78
BlueTrin
  • 9,610
  • 12
  • 49
  • 78
  • As I understand it, this behavior is determined by the compiler and not explicitly addressed in the C++ standard – CatShoes Aug 30 '12 at 19:04
  • 4
    Possible dup: http://stackoverflow.com/questions/949433/could-anyone-explain-these-undefined-behaviors-i-i-i-i-i-etc - this is covered in one of the answers. – Mat Aug 30 '12 at 19:04
  • Please close or remove my question if it is a dupe, I tried to find it was asked but did not formulate my search with the correct keywords. – BlueTrin Aug 30 '12 at 19:07
  • There was something asked a day or two ago that was very similar and featured a test case almost exactly like this. I think it was something like "Is the result 0, 1, or undefined?" – chris Aug 30 '12 at 19:09
  • 1
    [This answer](http://stackoverflow.com/a/4177063/947836) in particular explains this very nicely. – jrok Aug 30 '12 at 19:15
  • See for an explanation of why: http://stackoverflow.com/a/367690/14065 – Martin York Aug 30 '12 at 19:58

1 Answers1

6

This is undefined behavior. Literally any behavior is legal.

The passage that forbids that line of code is this:

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 between a[i] and i++ and the read to i in a[i] is not for the purpose of determining what value is stored in i by i++.

Dirk Holsopple
  • 8,731
  • 1
  • 24
  • 37
  • Thanks for the explanation, I added a link to the wiki page of sequence points – BlueTrin Aug 30 '12 at 19:08
  • 1
    sequence points have been removed from C++ and replaced with sequencing relationships between statements/sub-expressions. [see here](http://stackoverflow.com/a/10655884/365496). This changes some instances of undefined behavior to well-defined behavior, but not in this particular case case. – bames53 Aug 30 '12 at 19:09