views:

238

answers:

8

I'm new to c++ and am curious how the compiler handles lazy evaluation of booleans. For example,

if(A == 1 || B == 2){...}

If A does equal 1, is the B==2 part ever evaluated?

+10  A: 

No, the B==2 part is not evaluated. This is called short-circuit evaluation.

Edit: As Robert C. Cartaino rightly points out, if the logical operator is overloaded, short-circuit evaluation does not take place (that having been said, why someone would overload a logical operator is beyond me).

James McNellis
A: 

No it's not.

Same with &&, if one is wrong, it doesn't bother evaluating the other one.

Dan
A: 

B == 2 is never evaluated.

See Short-Circuit Evaluation for more information.

Nick Presta
+1  A: 

The B==2 part is not evaluated.

Be careful! Don't put something like ++B==2 over there!

eleven81
+1  A: 

C++ applies short circuiting to Boolean expression evaluation so, the B == 2 is never evaluated and the compiler may even omit it entirely.

D.Shawley
+2  A: 

The compiler handles this by generating intermediate jumps. For the following code:

if(A == 1 || B == 2){...}

compiled to pseudo-assembler, might be:

    load variable A
    compare to constant 1
    if equal, jump to L1
    load variable B
    compare to constant 2
    if not equal, jump to L2
L1:
    ... (complete body of if statement)
L2:
    (code after if block goes here)
Greg Hewgill
you don't know that. You compiler might decide that A is always 1 for instance and completely discard that check.
shoosh
That's true, but that's an optimisation and not relevant for this example.
Greg Hewgill
+1  A: 

This is short-circuit evaluation, as James says. Lazy evaluation is something entirely different.

Conrad Meyer
It's not something _entirely_ different. Short-circuit evaluation is a _form of_ lazy evaluation.
James McNellis
+7  A: 

Unless the || operator is overloaded, the second expression will not be evaluated. This is called "short-circuit evaluation."

In the case of logical AND (&&) and logical OR (||), the second expression will not be evaluated if the first expression is sufficient to determine the value of the entire expression.

In the case you described above:

if(A == 1 || B == 2){...}

...the second expression will not be evaluate because

TRUE || ANYTHING, always evaluates to TRUE.

Likewise,

FALSE && ANYTHING, always evaluates to FALSE, so that condition will also cause a short-circuit evaluation.

A couple of quick notes

  • Short circuit evaluation will not apply to overloaded && and || operators.
  • In C++, you are guaranteed that the first expression will be evaluated first. Some languages do not guarantee the order of evaluation and VB doesn't do short-circuit evaluation at all. Important to know if you are porting code.
Robert Cartaino
+1 for noting that overloaded logical operators are not short-circuit evaluated.
James McNellis