Is (--i == i++) an Undefined Behavior?

后端 未结 8 1969
离开以前
离开以前 2020-12-22 11:06

this question is related to my previous problem. The answer I got was \"It is an Undefined behavior.\"

Please anyone explain:

  • What is an undef
相关标签:
8条回答
  • 2020-12-22 11:50

    Yes, that expression is undefined behavior as well (in C and C++). See http://en.wikipedia.org/wiki/Sequence_point for some information on the rules; you can also search for "sequence point" more generally (that is the set of rules that your code violates).

    0 讨论(0)
  • 2020-12-22 12:04

    Undefined behavior == the result cannot be guaranteed to always be the same whenever you run it in the exact same conditions, or the result cannot be guaranteed to always be the same whenever you use different compilers or runtimes to execute it.

    In your code, since it is using a equal comparison operator which does not specify which side of the operands should be executed first, --i or i++ may end up running first, and your answer will depend on the actual implementation of the compiler. If --i is executed first, it will be 4 == 4, i=5; if i++ is implemented first, it will be 5 == 5, i=5.

    The fact that the answer may turn out to be the same does not prevent the compiler from warning you that this is an undefined operation.

    Now if this is a language that defines that the left hand side (or right hand side) should always be executed first, then the behavior will no longer be undefined.

    0 讨论(0)
提交回复
热议问题