Home > Backend Development > C++ > body text

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

Linda Hamilton
Release: 2024-10-29 12:36:02
Original
148 people have browsed it

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!