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

后端 未结 8 2022
离开以前
离开以前 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:39

    (This assumes C or C++.)

    Carl's answer is exact in general.

    In specific, the problem is what Jeremiah pointed out: sequence points.

    To clarify, the chunk of code (--i == ++i) is a single "happening". It's a chunk of code that's evaluated all at once. There is no defined order of what happens first. The left side could be evaluated first, or the right side could, or maybe the equality is compared, then i is incremented, then decremented. Each of these behaviors could cause this expression to have different results. It's "undefined" what will happen here. You don't know what the answer will be.

    Compare this to the statement i = i+1; Here, the right side is always evaluated first, then its result is stored into i. This is well-defined. There's no ambiguity.

    Hope that helps a little.

提交回复
热议问题