Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where do sequence points come from?

I know that writing something like

++a = a++;

Is not only unreadable but also violates the c/c++ sequence points.

Where do these limitations come from? How can one see those 'problems' before finding them as bugs?

like image 228
Artur Marianek Avatar asked Jun 25 '12 17:06

Artur Marianek


3 Answers

Basically there is a C++03 sequence point between each statement. For more information see the SO C++ FAQ. For even more information do consult the C++ standard, and keep in mind that in the C++11 standard sequence points were replaced with sequenced before and sequenced after relations.

To avoid problems, simply don't try to be too clever about doing a lot in each expression.

Don't try to do the compiler's job: leave that to the compiler. Your job is to write code that other humans can easily understand, i.e. clear code. Multiple updates and needless use of operators with side effects is not compatible with that.

Tip: sprinkle const just about everywhere possible.

That constrains the possible state changes that a reader must take into account.

like image 161
Cheers and hth. - Alf Avatar answered Oct 04 '22 16:10

Cheers and hth. - Alf


They come from the C or C++ standard, which effectively lists sequence points.1 In a few simple cases, your compiler may be able to warn you that you're invoking undefined behaviour, but not in the general case.

However, you're generally only ever violating sequence-point requirements if you're writing "interesting" code such as your example. The language standard could impose particular constraints on code such as this (which is what languages such as Java do), but there's not a great deal of upside, and the potential downside of preventing certain types of optimisation.


1. The terminology has changed slightly in C++11, but the principle is still largely the same, I think.
like image 36
Oliver Charlesworth Avatar answered Oct 04 '22 15:10

Oliver Charlesworth


How can one see those 'problems' before finding them as bugs?

Compile your program with strictest level and enable the settings for all warnings to be pointed out as errors. Most mainstream compilers do point out Undefined Behavior errors due to sequence points.

With gcc you can use:

-Wsequence-point

which shall point out sequence point problems. Note that it is enabled by default if you use -Wall.

Of course, the best way is to try and write more readable code which avoids sequence point mis-adventures.

like image 44
Alok Save Avatar answered Oct 04 '22 16:10

Alok Save