test321["abc"] = 1;
test321["abc"] = test321.count("abc") ? test321["abc"]++ : 0;
test321["abc"] = 1
test321["abc"] = 1;
test321["abc"] = test321.count("abc") ? test321["abc"]+1 : 0;
test321["abc"] = 2
Why is there a difference?
test321["abc"] = 1;
test321["abc"] = test321.count("abc") ? test321["abc"]++ : 0;
test321["abc"] = 1
test321["abc"] = 1;
test321["abc"] = test321.count("abc") ? test321["abc"]+1 : 0;
test321["abc"] = 2
Why is there a difference?
The line
test321["abc"] = test321.count("abc") ? test321["abc"]++ : 0;
has undefined behavior until C++17 since test321["abc"]
is modified in two ways:
It's best to avoid using such constructs. You can read more about it at Why are these constructs (using ++) undefined behavior in C?.
The second approach is well-behaved code and should be used for what you intend to do.
If you use C++17, both approaches should result in identical behavior.
The question you're posing, "Why is there a difference?", is less meaningful than you might expect, because your code invokes Undefined Behavior.
Consider the following code snippet which is, semantically, equivalent to what your code is doing:
int x = 1;
x = x++;
What is a logical result for x
? Is there a logical result?
Well, if you ask the C++ standard, the answer is that there is no logical result, and it leaves the result of an operation like this to be undefined. Any given compiler is given no restrictions or limitations on what it should do with code like this, so some compilers will work out that a logical result is for x
to equal 2, and some compilers will work out 1 instead. Some compilers might (rarely) do something else entirely.
For more on this particular phenomenon, see this related Question.
To avoid undefined behavior, you should prefer constructs like this:
auto & ref = test321["abc"];//We save the reference to avoid performance issues
//Note that the brackets operator will create an entry if it doesn't already exist, negating
//the need for a check to count(); count() will always return at least 1.
ref = 1;
ref = ref + 1;
Or
if(auto & ref = test321["abc"])
ref++;//Will only increment if value was not 0.