Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yet another question related to sequence points

Tags:

c++

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.

like image 526
AMS Avatar asked Nov 22 '10 14:11

AMS


3 Answers

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.

like image 152
Binary Worrier Avatar answered Sep 20 '22 03:09

Binary Worrier


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.

like image 21
sharptooth Avatar answered Sep 23 '22 03:09

sharptooth


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.

like image 41
Inverse Avatar answered Sep 22 '22 03:09

Inverse