Home  >  Article  >  Backend Development  >  Does Fourth Edition \"The C Programming Language\" Code Exhibit Well-Defined Behavior?

Does Fourth Edition \"The C Programming Language\" Code Exhibit Well-Defined Behavior?

Barbara Streisand
Barbara StreisandOriginal
2024-10-23 22:14:29183browse

Does Fourth Edition

Does Code from "The C Programming Language" 4th Edition Have Well-Defined Behavior?

The code in question exhibits unspecified behavior, despite not invoking undefined behavior. This is due to unspecified order of evaluation of sub-expressions, particularly regarding the calls to s.replace().

Principle of Unspecified Sub-Expression Evaluation

Function arguments have an unspecified order of evaluation, meaning that the evaluation order of individual function arguments cannot be assumed. In this case, the arguments to s.find() are not guaranteed to be evaluated before or after s.replace().

Evaluation Order Impacts

Depending on the evaluation order, the results of s.find() can be altered by the side effects of s.replace(). This is because s.replace() modifies the length of the string, affecting the result of subsequent s.find() calls.

Actual Evaluation Differences

In the test provided, clang evaluates s.find("even") before s.replace(0, 4, ""), while gcc evaluates them potentially in the opposite order. This difference in order leads to different results in the chained function calls.

C 17 Changes

In C 17, the evaluation order for postfix expressions (like chain calls) has been strengthened. The initialization of parameters (including side effects) in function arguments is now indeterminately sequenced with respect to other parameters. This ensures that code like the one in question will have well-specified behavior.

The above is the detailed content of Does Fourth Edition \"The C Programming Language\" Code Exhibit Well-Defined Behavior?. 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