Home > Backend Development > C++ > Why Does `mp[10] = mp.size()` Output `1` in C Even If `mp` is Empty?

Why Does `mp[10] = mp.size()` Output `1` in C Even If `mp` is Empty?

Linda Hamilton
Release: 2024-10-30 20:57:30
Original
984 people have browsed it

Why Does `mp[10] = mp.size()` Output `1` in C   Even If `mp` is Empty?

Order of Evaluation Conundrum in C Assignment Statements

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template