4

Possible Duplicate:
Undefined Behavior and Sequence Points

#include <iostream>
using namespace std;

int main()
{
int x[3] = {};
int i=0;
x[i] = i++;
cout << x[0] << " " << x[1] << endl;
return 0;
}

Codepad is giving me this: Line 9: warning: operation on 'i' may be undefined Why is the operation undefined?

Community
  • 1
  • 1
user52343
  • 773
  • 1
  • 7
  • 19
  • 2
    I'm constantly surprised that this question, after having been asked at least 1000 times straight, still generates 5 upvotes – sehe Jun 21 '12 at 06:24

2 Answers2

7

Clearly explained here: C-Faq

Why doesn't this code: a[i] = i++; work?

The subexpression i++ causes a side effect--it modifies i's value--which leads to undefined behavior since i is also referenced elsewhere in the same expression. There is no way of knowing whether the reference will happen before or after the side effect--in fact, neither obvious interpretation might hold; see question 3.9. (Note that although the language in K&R suggests that the behavior of this expression is unspecified, the C Standard makes the stronger statement that it is undefined--see question 11.33.)

Relevant Standard Quotation is as follows:

C++03 5 Expressions [expr]:
Para 4:

....
Between the previous and next sequence point a scalar object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be accessed only to determine the value to be stored. The requirements of this paragraph shall be met for each allowable ordering of the subexpressions of a full expression; otherwise the behavior is undefined.

Alok Save
  • 202,538
  • 53
  • 430
  • 533
  • The [SO faq](http://stackoverflow.com/questions/4176328/undefined-behavior-and-sequence-points) also has the same example `a[i] = i++;` with a nice explanation. – Jesse Good Jun 21 '12 at 05:56
  • @JesseGood: It has a *similar* but not exactly same example.Ofcourse the explanation is very good.It provides a very good generic explantion but sometimes its tricky and not so evidently clear as to how some code examples obey the first rule of the standard quote but disobey the second rule and lead to a UB. – Alok Save Jun 21 '12 at 06:03
5

You are modifying a variable and using its value without an intervening sequence point. What do you expect is the value of i when x[i] appears? Because whatever you expect, you'd be wrong to expect that.

Benjamin Lindley
  • 101,917
  • 9
  • 204
  • 274