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)
i++
--- value of i
is 1++i
--- value of i
is 2j
and do the side effect of i++
(the order of this step is undefined too but we don't care because it won't change the result)case 2)
i++
--- value of i
is 1i++
--- value of i
is 2++i
--- current value of i
is 3j
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:
++i
--- value of i
is 2i++
--- value of i
is 2j
and do the side effect of i++
(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
int j = ++i + i++;
is still undefined behavior since ++i
and i++
can be processed simultaneously in multiple pipelines in some CPUs, which will lead to unpredictable results.