Home > Backend Development > C++ > body text

Why Does Assigning to a Map Element in C Result in an Unexpected Size?

DDD
Release: 2024-11-01 08:36:02
Original
170 people have browsed it

 Why Does Assigning to a Map Element in C   Result in an Unexpected Size?

Evaluation Order of Assignment Statements in C

A puzzling output can be obtained when assigning a value to a map:

<code class="cpp">map<int, int> mp;
printf("%d ", mp.size());
mp[10] = mp.size();
printf("%d\n", mp[10]);</code>
Copy after login

This code prints:

0 1
Copy after login

This result may seem counterintuitive, as one might expect the map size to be 1 after the assignment. However, the evaluation order of the assignment statement plays a crucial role here.

The left-hand side of the assignment mp[10] returns a reference to the underlying value of the map element. Simultaneously, this action creates a new value for the mp[10] element. Only after this operation is the right-hand side evaluated, using the newly calculated size of the map.

This behavior is not explicitly stated in the C standard but falls under unspecified behavior. A recent proposal, N4228, aims to refine the order of evaluation rules to specify such cases.

The relevant section of the draft C 11 standard (1.9) states that evaluations of subexpressions of individual expressions are generally unsequenced. However, function calls (such as operator [] and size()) are sequenced before the execution of the called function's body.

Therefore, the right operand of the assignment expression is sequenced after the left operand, resulting in the observed behavior. This means that the order of evaluation is as follows:

  1. Evaluate the right operand: mp.size()
  2. Create the value for the left operand: mp[10]
  3. Assign the value of the right operand to the left operand

An update to the C standard is expected to specify this behavior, making it clear that the right operand of an assignment expression is sequenced before the left operand.

The above is the detailed content of Why Does Assigning to a Map Element in C Result in an Unexpected Size?. 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!