Short Circuit Evaluation

Short-circuit evaluation is a strategy most programming languages (including C++) use to avoid unnecessary work. For example, say we had a conditional like this:

if (itIsFriday && itIsRaining) { cout << "board games at my place!" << endl; }

Let's say itIsFriday is false. Because C++ short-circuits evaluation, it wouldn't bother checking the value of itIsRaining—it knows that either way the condition is false and we won't print the invitation to board game night.

We can use this to our advantage. For example, say we have a check like this:

auto it = friends.find("Becky"); if (it->second->isFreeThisFriday()) { inviteToBoardGameNight(it->second); }

What happens if "Becky" isn't in our friends unordered map? Since the iterator returned from friends.find("Becky") will be map::end, it's undefined what will happen when we try to dereference it. We'll probably get a segfault.

Instead, we could first confirm that Becky and I are still on good terms:

auto it = friends.find("Becky"); if (it != friends.end() && it->second->isFreeThisFriday()) { inviteToBoardGameNight(it->second); }

This way, if "Becky" isn't in friends, C++ will skip the second check about Becky being free and avoid dereferencing map::end.

This is all hypothetical, of course. It's not like things with Becky are weird or anything. We're totally cool. She's still in my friends unordered map for sure and I hope I'm still in hers and Becky if you're reading this I just want you to know you're still in my friends unordered map.

. . .