Yes i read the article on sequence points. However i could not understand why ++i = 2
would invoke undefined behavior? The final value of i
would be 2 regardless of anything, so how come the expression is ub?
code snippet
int main()
{
int i =0;
++i=2;
return 0;
}
Sorry my english is not very good.
It looks obvious to you, because obviously i
will first be assigned i+1
, then second be assigned the value 2
.
However, both of these assignments happen within the same sequence point, therefore it's up to the compiler to which happens frist and which happens second, therefore different compiler implementations can generate code that will give different results, therefore it's UB.
You observe that value will be what you claim, that's how UB can manifest itself among other possible scenarios. The program might output what you expect, output some unrelated data, crash, corrupt data or spend all your money ordering pizza. Once C++ standard says that some construct is UB you should not expect any specific behavior. Observed results can vary from one program run to another.
The undefined behavior occurs because a compiler could implement the following code:
++i = 2;
as either:
i = 2;
++i;
or
++i;
i = 2;
It's unspecified in the language, a compiler could choose to implement either of the above. The first would produce 3
and the second 2
. So it's undefined.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With