Home > Backend Development > C++ > Is `i = i 1` Legally Defined in C 17?

Is `i = i 1` Legally Defined in C 17?

Linda Hamilton
Release: 2024-10-29 03:02:02
Original
663 people have browsed it

 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:

  • Value computations of the right and left operands are sequenced before the actual assignment.
  • However, there was no specific sequencing requirement between the assignment itself and potential side effects in the right-hand side (RHS) expression.

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:

  1. Value computation of right operand (RHS): i 1

    • Increment i using postfix (side effect).
    • Add 1 to the incremented value.
  2. Sequencing of RHS before LHS:

    • All side effects in the RHS (including the increment) occur.
  3. Value computation of left operand (LHS): i

    • Current value of i is used.
  4. Assignment:

    • Assign the result of the RHS to the LHS.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template