Evaluation Order of Assignment Statements in C
A puzzling output can be obtained when assigning a value to a map:
map mp;
printf("%d ", mp.size());
mp[10] = mp.size();
printf("%d\n", mp[10]);
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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3