Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is (a=1)=2 undefined behaviour in C++98?

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 ?

like image 632
inverse Avatar asked Apr 01 '20 03:04

inverse


People also ask

What are undefined behavior in C?

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.

What is undefined value in C?

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.

Is unspecified behavior undefined behavior?

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.

Why does C allow undefined behavior?

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.


1 Answers

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

like image 180
M.M Avatar answered Sep 30 '22 17:09

M.M