Why is this Undefined Behavior?

泄露秘密 提交于 2019-12-01 05:42:00
Steve Jessop

It isn't undefined.

Answered here for C, Sequence points and partial order

I think the same applies in C++ (and here's my response before I saw that link):

The comma operator introduces a sequence point (and constrains to some extent the order in which the expression must be evaluated - left before right), so:

  • the two modifications of i are separated by a sequence point (the second comma).
  • the modification of i in i++ is separated from everything else by sequence points.
  • the modification of i by = is not separated from the last occurrence of i in the expression, but that's OK because we're allowed to access i and modify it without an intervening sequence point, provided that the access is "to determine the value to be stored" (5/4).
  • As Als says, in practice it wouldn't matter whether that code has defined behavior or not provided that everyone had the basic common sense not to write it ;-)

Because it isn't defined in the standard which of the post-increment or the assignment will take place first; it is left to the compiler implementation to decide their order.

It is undefined in C++ to assign an incremented value to itself:

i = i++

What should i be after this? Should it be the previous value or one plus the previous value? The order of execution is left to the compiler, so different platforms will have different results.

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