Reputation: 12371
I have such a piece of code:
std::map<int, int> mp;
// do something
auto itor = mp.find(some_value);
if (itor != mp.end() && itor->second == some_other_value) {
// do something
}
I'm worrying about which expression would be evaluated first, itor != mp.end()
or itor->second == some_other_value
?
If the second one is evaluated firstly (because of some compiler-optimization maybe?), it might get an undefined behavior because itor == mp.end()
may be true.
Should I worry about this issue so that I have to code like this:
if (itor != mp.end) {
if (itor->second == some_other_value) {
// do something
}
}
Upvotes: 0
Views: 38
Reputation: 550
Logical And - && - expression is evaluated left to right so itor != mp.end()
will be evaluated initially. Moreover, it returns true only if both expressions return true, hence if the first one is false the second one is not checked.
so the first case should work.
Upvotes: 0
Reputation: 16660
No worries; your code is fine.
If the first condition of if (a && b)
is false, then the second condition is not evaluated.
Look up "short-circuit evaluation"
Wikipedia has some info.
Upvotes: 1