Where do the sequence points come from?

I know I'm writing something like

++a = a++; 

It is not only unreadable, but also breaks the points of the c / C ++ sequence.

Where do these restrictions come from? How can one see these “problems” before finding them as errors?

+8
c ++ c sequence-points
source share
3 answers

Basically, there is a C ++ 03 sequence point between each statement. For more information, see the SO C ++ FAQ . For more information, consult the C ++ standard and keep in mind that in C ++ 11 the standard sequence points were replaced by the previously sequenced ones and ordered after the relationship.

To avoid problems, just do not try to be too smart, doing a lot in each expression.

Do not try to complete the compiler task: leave it to the compiler. Your task is to write code that is easy to understand for other people, i.e. clear code . Multiple updates and unnecessary use of operators with side effects are incompatible with this.

Tip: sprinkle const almost everywhere.

This holds back possible state changes that the reader should consider.

+8
source share

They come from the C or C ++ standard, which effectively lists the points of a sequence . 1 In a few simple ways, your compiler may warn you that you are calling undefined behavior, but not in the general case.

However, you, as a rule, only violate the requirements of the sequence if you write "interesting" code, for example, your example. A language standard may impose special restrictions on code such as this (what languages ​​such as Java are), but there is not much potential and potential drawback in preventing certain types of optimization.


<Sub> 1. In my opinion, the terminology has changed a bit in C ++ 11, but the principle is still pretty much the same.
+7
source share

How can one see these “problems” before finding them as errors?

Compile your program with a strict level and include the parameters of all warnings as errors. Most major compilers point to Undefined behavior errors due to sequence points.

With gcc you can use:

 -Wsequence-point 

which should indicate consistency issues. Please note that it is enabled by default if you use -Wall .

Of course, the best way is to try to write more readable code that avoids erroneous sequence adventures.

+4
source share

All Articles