Home > Backend Development > C++ > body text

Why Does Assigning a Map Value in C Produce Unexpected Results?

DDD
Release: 2024-10-28 15:10:02
Original
515 people have browsed it

 Why Does Assigning a Map Value in C   Produce Unexpected Results?

Evaluation Order in C Assignment Statements

When assigning a value to a map in C , the order of evaluation can lead to counterintuitive results. Consider the following code:

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

This code prints 0 and then 1, whereas one might expect 0 and 0. This is because:

  1. Right-to-Left Evaluation: Assignment operators in C associate from right to left, meaning that mp[10] is evaluated before mp.size().
  2. Temporary Reference: The left-hand side of the assignment mp[10] creates a temporary reference to the underlying map element. This element is initially uninitialized, so mp.size() initially returns 0.
  3. Value Modification: The assignment mp[10]=mp.size() sets the value of mp[10] to the current size of the map, which is 0.
  4. Reference Life Extension: The assignment temporarily extends the lifetime of the temporary reference created by mp[10].
  5. Final Evaluation: mp[10] is now pointing to the modified element, so printf("%d", mp[10]); prints the updated value of 1.

Unspecified Behavior

This particular behavior is unspecified in the C standard. However, a recent proposal (N4228) seeks to clarify the order of evaluation in such cases.

Section [expr.ass]p1 of the revised proposal states that:

"The right operand is sequenced before the left operand."

This means that in the above example, mp.size() would be evaluated before mp[10], resulting in the expected output of 0 and 0.

Update

It is important to note that in C 17, this behavior has been specified in the standard, as per revision 3 of proposal p0145. The right operand is now explicitly sequenced before the left operand in assignment statements.

The above is the detailed content of Why Does Assigning a Map Value in C Produce Unexpected Results?. 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
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!