Home  >  Article  >  Backend Development  >  Why is \"i = i 1\" legal in C 17 but undefined behavior in C 11?

Why is \"i = i 1\" legal in C 17 but undefined behavior in C 11?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-27 09:53:30262browse

Why is

Making i = i 1 Legal in C 17

In C 11, the expression "i = i 1" is undefined behavior due to insufficient sequencing guarantees. However, in C 17, this expression becomes legal. Here's why:

C 11

In C 11, the sequencing rules for the assignment operator (=) stated that the assignment was sequenced after the value computation of the right and left operands. However, no specific rules existed for the relative sequencing of the assignment and side effects in the right operand. This lack of sequencing led to undefined behavior in cases like "i = i 1," where the side effect (incrementing i) and the assignment were potentially unsequenced.

C 17

C 17 introduces a new sequencing rule for the assignment operator: "The right operand is sequenced before the left operand." This means that all side effects and value computations within the right operand are fully sequenced before any action takes place on the left operand, including the assignment itself.

Effect on "i = i 1"

With the new sequencing rule in C 17, the expression "i = i 1" becomes legal because the side effect of incrementing i (performed by the postfix operator) is now guaranteed to happen before the assignment. Therefore, the act of assigning the value of "i 1" to i is fully isolated from the side effect, eliminating the undefined behavior that existed in C 11.

In summary, the change in sequencing rules for the assignment operator in C 17 ensures that the evaluation of "i = i 1" follows a specific sequence, allowing the side effect of incrementing i to precede the assignment itself, resolving the undefined behavior that existed in C 11.

The above is the detailed content of Why is \"i = i 1\" legal in C 17 but undefined behavior in C 11?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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