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>
This code prints:
0 1
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:
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!