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?
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.
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.
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.
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