How does C++ handle &&? (Short-circuit evaluation)

Aleksandrs Ulme picture Aleksandrs Ulme · Mar 6, 2011 · Viewed 38.1k times · Source

When encountering a (bool1 && bool2), does c++ ever attempts to check bool2 if bool1 was found false or does it ignore it the way PHP does?

Sorry if it is too basic of a question, but I really could not find a mentioning of that neither in Schildt nor on the Internet.

Answer

jason picture jason · Mar 6, 2011

Yes, the && operator in C++ uses short-circuit evaluation so that if bool1 evaluates to false it doesn't bother evaluating bool2.

"Short-circuit evaluation" is the fancy term that you want to Google and look for in indexes.

The same happens with the || operator, if bool1 evaluates to true then the whole expression will evaluate to true, without evaluating bool2.

In case you want to evaluate all expressions anyway you can use the & and | operators.