This question already has an answer here:
- Why are these constructs using pre and post-increment undefined behavior? 14 answers
Imagine that we have the code below:
int i = 1;
int j = i++ + ++i;
I know that this is a Undefined Behavior, because before the semicolon, which is a sequence point, the value of i
has been changed more than once. It means that the compiler may have two possibilities even if the precedence of operator plus is Left-to-Right:
case 1)
- take the value of
i++
--- value ofi
is 1 - take the value of
++i
--- value ofi
is 2 - do the operator plus and assign the result which is 3 to
j
and do the side effect ofi++
(the order of this step is undefined too but we don't care because it won't change the result)
case 2)
- take the value of
i++
--- value ofi
is 1 - do the side effect of
i++
--- value ofi
is 2 - take the value of
++i
--- current value ofi
is 3 - do the operator plus and assign the result which is 4 to
j
If nothing is wrong here, I have a question:
int j = ++i + i++;
Is the code above still an Undefined Behavior?
In my opinion, there is only one possibility:
- do the side effect of
++i
--- value ofi
is 2 - take the value of
i++
--- value ofi
is 2 - do the operator plus and assign the result which is 4 to
j
and do the side effect ofi++
(the order of this step is undefined too but we don't care because it won't change the result)
Am I right?
Btw I've read this link:
Undefined behavior and sequence points