0

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?

solarflare
  • 423
  • 3
  • 14

2 Answers2

4

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.

mlukas
  • 70
  • 7
  • 2
    I believe a notable exception is if the || or && operators are overloaded. –  Jul 24 '19 at 00:44
  • 1
    Note: if a class provides an `operator||` or `operator&&` the short-circuiting behavior does NOT apply. (Generally recommended *NOT* providing that kind of operator overloading.) – Eljay Jul 24 '19 at 01:13
  • Yeah, that's true. Hopefully no one would try to confuse people like that :) – mlukas Jul 24 '19 at 01:41
1

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.

Miles Budnek
  • 28,216
  • 2
  • 35
  • 52
  • 1
    "Both sides of the expression will be evaluated." which is why you should not normally overload these operators. –  Jul 24 '19 at 00:42