关于c ++:为什么增量操作如“a [i] = i ++;”会导致未定义的行为?

Why does increment operation like “a[i] = i++;” result in undefined behavior?

本问题已经有最佳答案,请猛点这里访问。

Possible Duplicate:
Undefined Behavior and Sequence Points

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
using namespace std;

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

代码板告诉我:第9行:警告:"i"上的操作可能未定义为什么操作未定义?


这里解释清楚:C-FAQ

为什么这个代码:a[i] = i++;不起作用?

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.)

相关标准报价如下:

C++ 03 5表达式[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.


您正在修改一个变量并使用它的值,而不需要中间的序列点。当x[i]出现时,您预计i的价值是多少?因为无论你期望什么,你都错了。