Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.


C++ does use short-circuit logic, so if bool1 is false, it won't need to check bool2.

This is useful if bool2 is actually a function that returns bool, or to use a pointer:

if ( pointer && pointer->someMethod() )

without short-circuit logic, it would crash on dereferencing a NULL pointer, but with short-circuit logic, it works fine.


That is correct (short-cicuit behavior). But beware: short-circuiting stops if the operator invoked is not the built-in operator, but a user-defined operator&& (same with operator||).

Reference in this SO


The && operator short circuits in C++ - if bool1 was false in your example, bool2 wouldn't be checked/executed.


This is called short-circuit evaluation (Wikipedia)

The && operator is a short circuit operator in C++ and it will not evaluate bool2 if bool1 is false.