Another question related to sequence points

Yes, I read an article on sequence points . However, I could not understand why ++i = 2 would refer to undefined behavior? The final value of i will be 2 regardless of anything, so how did the expression ub turn out?

code snippet

 int main() { int i =0; ++i=2; return 0; } 

Sorry, my English is not very good.

+7
c ++
source share
6 answers

You have noticed that it will be that you are claiming that UB can prove itself among other possible scenarios. The program can output what you expect, output some unrelated data, crash, corrupted data, or spend all your money on ordering pizza. Once the C ++ standard says some UB construct, you should not expect any specific behavior. Observed results may vary from one program to another.

+9
source share

This is obvious to you, because obviously i will be assigned first i+1 , and then second will be assigned the value 2 .

However, both of these assignments are performed in the same sequence, therefore they relate to the compiler to which frist occurs, and what happens secondly, therefore different compiler implementations can generate code that will give different results, therefore it is UB .

+11
source share

Undefined behavior occurs because the compiler can implement the following code:

 ++i = 2; 

as:

 i = 2; ++i; 

or

 ++i; i = 2; 

It is not defined in the language, the compiler can choose one of the above. The first would create 3 and the second 2 . So undefined.

+2
source share

Call ++i = 2; itself does not cause undefined behavior; any compiler can, if it wants, perform a very specific action when this code is reached. However, the C ++ standard states that this operation is undefined, so the compiler may do something unexpected (for example, delete all files on the C drive or send a text message to dad) and still be a compatible compiler. The only thing that this UB does is that the standard says that it is UB.

Perhaps the most important point is that one version of the compiler can do something different from the next version of the same compiler.

+1
source share

From the same link that you provide:

  • In addition, the previous value should only be accessed to determine the value to be stored.

What does it mean? This means that if an object is written with the full expression, any access to it inside the same expression must be directly involved in the calculation of the value that must be written.

Here, on the left side of the = operator, access to i not involved in calculating the recorded value.

0
source share

++ i (should be) rvalue and therefore cannot be used as lvalue, but (++ i) = 2; should work fine. I do not believe that it is UB, but, as always, I can be mistaken.

0
source share

All Articles