Home >Backend Development >C++ >How Does the Order of Evaluation in C Assignment Statements Affect the Output?
Order of Evaluation in Assignment Statements in C
In the given code snippet:
map<int, int> mp;<br>printf("%d ", mp.size());<br>mp[10]=mp.size();<br>printf("%dn", mp[10]);<br>
the seemingly counterintuitive output of "0 1" arises from the unspecified order of evaluation of sub-expressions in assignments.
As per the C standard, the order of evaluation in assignment statements is undefined. However, the behavior is as follows:
Therefore, in the code snippet, mp.size() is evaluated to 0 and assigned to mp[10]. Then, mp[10] is evaluated again, which now returns the value it was assigned (1).
Despite being unspecified in the current C standard, this behavior has been addressed in a recent proposal (N4228):
N4228 proposes refining the order of evaluation rules to make it well-defined for certain cases, including the one above. According to the proposal, the right operand of an assignment is sequenced before the left operand.
This means that in C 17 and beyond, the code snippet's behavior will likely be well-defined and result in an output of "1 1."
The above is the detailed content of How Does the Order of Evaluation in C Assignment Statements Affect the Output?. For more information, please follow other related articles on the PHP Chinese website!