The behavior is unspecified, but not undefined.
Notice, that in the expression:
word_count["a"] = word_count.count("a") == 0 ? 1 : 2;
// ^
The assignment operator marked with ^
is the built-in assignment operator, because std::map
's operator []
returns a size_t&
.
Per Paragraph 5.17/1 of the C++11 Standard on the built-in assignment operator(s):
The assignment operator (=) and the compound assignment operators all group right-to-left. [..] In all cases, the assignment is sequenced after the value computation of the right and left operands, and before the value computation of the assignment expression. With respect to an indeterminately-sequenced function call, the operation of a compound assignment is a single evaluation.
This means that in a built-in assignment such as:
a = b
First the operands are evaluated (in unspecified order), then the assignment is performed, and finally the value computation of the whole assignment expression is performed.
Considering the original expression:
word_count["a"] = word_count.count("a") == 0 ? 1 : 2;
// ^
Because of the paragraph quoted above, in no case there are two unsequenced assignments to the same object: the assignment marked with ^
will always be sequenced after the assignment performed by operator []
(as part of the evaluation of the left hand side expression) in case the key "a"
is not present in the map.
However, the expression will have a different outcome based on which side of the assignment is evaluated first. Thus, the behavior is unspecified, but not undefined.