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

为君一笑 提交于 2019-11-29 08:24:30

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!