In C , the order of evaluation for assignment statements isn't always intuitive. Consider the following code:
<code class="cpp">map<int, int> mp; printf("%d ", mp.size()); mp[10]=mp.size(); printf("%d\n", mp[10]);</code>
This seemingly straightforward code surprisingly outputs "0 1," which may not be what you'd expect.
To understand why, we must delve into the specifics of C evaluation order. Assignment statements, as specified by [expr.ass](https://en.cppreference.com/w/cpp/language/operator_assignment) of the C standard, "all group right-to-left." This means that the right operand is evaluated before the left operand. Additionally, the C standard specifies that in an assignment operation, "the assignment is sequenced after the value computation of the right and left operands, and before the value computation of the assignment expression."
In our code, the left operand is mp[10], which is an assignment operation itself. The right operand is mp.size(), which evaluates to 0 since the map is initially empty. So, the code effectively assigns mp[10] to 0. However, the assignment operation is sequenced before the value computation of mp[10]. This means that first, the value of mp[10] is modified, creating a new entry in the map and setting it to 0. Only then is the value of mp[10] evaluated, revealing the newly created entry with a value of 1.
This is a clear example of the seemingly unexpected order of evaluation in C . To avoid such surprises, it's essential to be aware of the standard's specifications and to consider the order in which operations will be executed. In cases where the order is not crucial or the potential for undefined behavior exists, explicit parentheses can be used to control the evaluation order.
The above is the detailed content of Why Does `mp[10] = mp.size()` Output `1` in C Even If `mp` is Empty?. For more information, please follow other related articles on the PHP Chinese website!