Similar codes for example (a+=1)%=7;
, where a is an int
variable.
We know that operator +=
or =
is not a sequence point, therefore we have two side-effects between two adjcent sequence points. (we are using cpp98's sequence point rules here)
However, assignment operators like +=
or =
guarantees to return the lvalue after assignment, which means the order of execution is to some degree "defined".
So is that an undefined behaviour ?
So, in C/C++ programming, undefined behavior means when the program fails to compile, or it may execute incorrectly, either crashes or generates incorrect results, or when it may fortuitously do exactly what the programmer intended.
In computing (particularly, in programming), undefined value is a condition where an expression does not have a correct value, although it is syntactically correct. An undefined value must not be confused with empty string, Boolean "false" or other "empty" (but defined) values.
Undefined Behavior results in unpredicted behavior of the entire program. But in unspecified behavior, the program makes choice at a particular junction and continue as usual like originally function executes.
C and C++ have undefined behaviors because it allows compilers to avoid lots of checks. Suppose a set of code with greater performing array need not keep a look at the bounds, which avoid the needs for complex optimization pass to check such conditions outside loops.
(a=1)=2
was undefined prior to C++11, as the =
operator did not introduce a sequence point and therefore a
is modified twice without an intervening sequence point. The same applies to (a+=1)%=7
The text was:
Between the previous and next sequence point a scalar object shall have its stored value modified at most once by the evaluation of an expression.
It's worth mentioning that the description of the assignment operator is defective:
The result of the assignment operation is the value stored in the left operand after the assignment has taken place; the result is an lvalue.
If the result is an lvalue then the result cannot be the stored value (that would be an rvalue). Lvalues designate memory locations. This sentence seems to imply an ordering relation, but regardless of how we want to interpret it, it doesn't use the term "sequence point" and therefore the earlier text about sequence points applies.
If anything, that wording casts a bit of doubt on expressions like (a=1) + 2
. The C++11 revision of sequencing straightened out all these ambiguities.
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