In an OR evaluation does C++ continue evaluating past the first TRUE it finds?
ie.
if(Foo() || Bar())
{
//..
}
If Foo() returns true will Bar() be skipped completely or will it also run that function?
In an OR evaluation does C++ continue evaluating past the first TRUE it finds?
ie.
if(Foo() || Bar())
{
//..
}
If Foo() returns true will Bar() be skipped completely or will it also run that function?
Operators && and || perform so called short-circuit evaluation, which means they do not evaluate the second operand if the result is known after evaluating the first. So no, Bar()
would not be evaluated in this case.
EDIT: That's the built-in functionality, as other people said. If they are overloaded, you obviously can't rely on it anymore.
The built-in ||
operator short-circuits. The left-hand expression is guaranteed to be evaluated first, and if the result is true
, the right-hand expression is not evaluated.
The &&
operator is the opposite. The left-hand expression is evaluated first and if it evaluates to false
then the right-hand expression is not evaluated.
Note that this does not hold for user-defined operator||
and operator&&
overloads. Those do not provide short-circuit evaluation. Both sides of the expression will be evaluated.