Home >Backend Development >C++ >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:
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!