Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ short-circuiting of booleans

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?

like image 277
tinkertime Avatar asked Nov 25 '09 18:11

tinkertime


4 Answers

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 evaluated 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. That's important to know if you are porting code.
like image 155
Robert Cartaino Avatar answered Nov 19 '22 17:11

Robert Cartaino


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).

like image 27
James McNellis Avatar answered Nov 19 '22 19:11

James McNellis


The B==2 part is not evaluated.

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

like image 1
eleven81 Avatar answered Nov 19 '22 18:11

eleven81


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

like image 1
D.Shawley Avatar answered Nov 19 '22 18:11

D.Shawley