Home >Backend Development >C++ >Is `i = i 1` Legally Defined in C 17?
Legality of i = i 1 in C 17
C 17 introduced a subtle yet significant change that legalized the expression i = i 1;, which was previously undefined behavior in C 11.
Before C 17
In C 11, the evaluation order of an assignment expression was specified as follows:
In the case of i = i 1;, this meant that the side effect of incrementing i using the postfix operator could occur before or after the assignment. This lack of sequencing led to undefined behavior.
Changes in C 17
C 17 introduced an additional sentence to the specification of the assignment operator: "The right operand is sequenced before the left operand." This seemingly innocuous addition has far-reaching implications.
By sequencing the RHS before the LHS, C 17 now ensures that any side effects in the RHS are guaranteed to occur before the assignment itself. This effectively isolates the assignment action from any potential undefined behavior.
Rewriting the Example
To illustrate this change, let's break down the evaluation of i = i 1; in C 17:
Value computation of right operand (RHS): i 1
Sequencing of RHS before LHS:
Value computation of left operand (LHS): i
Assignment:
By ensuring that all side effects in the RHS precede the assignment, C 17 definitively eliminates the possibility of undefined behavior in such expressions.
The above is the detailed content of Is `i = i 1` Legally Defined in C 17?. For more information, please follow other related articles on the PHP Chinese website!