Avatar ·

What are sequence points and how are they related to undefined behavior in C++?

Hi everyone! I started learning C++ and encountered a very strange situation. I write simple code:\n\n```cpp\nint i = 0;\nint result = i++ + i++;\n```\n\nI expected result to be 1 (0 + 1), but the compiler gives either 0, 1, or some other number. And if I write `i = i++ + 1`, the result is completely unpredictable. I was told this is related to "sequence points" and "undefined behavior". But I don't understand what that is. Can you explain in simple terms? Why can't the compiler just execute operations left to right? And how do I know when code is safe and when it's not? Please provide examples of correct and incorrect code. <<>>

What are sequence points?

Sequence points