Home  >  Article  >  Backend Development  >  How Does the Order of Evaluation in C Assignment Statements Affect the Output?

How Does the Order of Evaluation in C Assignment Statements Affect the Output?

Linda Hamilton
Linda HamiltonOriginal
2024-10-29 12:36:02140browse

How Does the Order of Evaluation in C   Assignment Statements Affect the Output?

Order of Evaluation in Assignment Statements in C

In the given code snippet:

map<int, int> mp;<br>printf("%d ", mp.size());<br>mp[10]=mp.size();<br>printf("%dn", mp[10]);<br>

the seemingly counterintuitive output of "0 1" arises from the unspecified order of evaluation of sub-expressions in assignments.

As per the C standard, the order of evaluation in assignment statements is undefined. However, the behavior is as follows:

  1. The right side of the assignment (in this case, mp.size()) is evaluated first.
  2. The left side of the assignment (mp[10]) is modified to reference the underlying value returned by the right side.
  3. The left side then evaluates its value again to use in the assignment.

Therefore, in the code snippet, mp.size() is evaluated to 0 and assigned to mp[10]. Then, mp[10] is evaluated again, which now returns the value it was assigned (1).

Despite being unspecified in the current C standard, this behavior has been addressed in a recent proposal (N4228):

N4228 proposes refining the order of evaluation rules to make it well-defined for certain cases, including the one above. According to the proposal, the right operand of an assignment is sequenced before the left operand.

This means that in C 17 and beyond, the code snippet's behavior will likely be well-defined and result in an output of "1 1."

The above is the detailed content of How Does the Order of Evaluation in C Assignment Statements Affect the Output?. 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