Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ lazy evaluation of boolean or in function call expression

Quick question, in c++ is this expression lazily evaluated?

bool funca();
bool funcb();

funca() || funcb(); // line in question

Obviously this is (potentially) just shorthand for the following:

bool funca();
bool funcb();

if (!funca()) {
    funcb();
}

// or even more concisely:

if (!funca()) funcb();

Will c++ evaluate that original line in question as I'm hoping it will? Thanks.

like image 929
eatonphil Avatar asked Nov 18 '13 02:11

eatonphil


3 Answers

In C/C++ the logical operators short-circuit. In a || b if a is true b is not evaluated and in a && b if a is false b is not evaluated.

Careful: this only happens with && and ||, not with | and &.

like image 65
Mihai Maruseac Avatar answered Nov 09 '22 11:11

Mihai Maruseac


It's called a short-circuit evaluation. But, yes - it's lazy, with respect to "||", in that if the condition must evaluate to true then it stops (e.g. if (a || b) will not evaluate b if a is true). And similarly with "&&" in that if (a && b) where a is false b is not evaluated.

like image 25
Elliott Frisch Avatar answered Nov 09 '22 11:11

Elliott Frisch


No. Lazy evaluation means that an subexpression is evaluated only when the expression in which it is contained is needed. Since you discard the result of the full expression, lazy evaluation would evaluate nothing.

If you had written writeBoolean(funcA() || funcB()); lazy evaluation would have evaluated funcA() since that's definitely necessary, and possibly funcB.

But that's not how C++ works; C++ does not have lazy evaluation. Even if you discard the result of an expression, it's still evaluated. You do get short-circuit evaluation. Whether funcB is called does not depend on use of the full expression, but it does depend on the result of funcA.

like image 31
MSalters Avatar answered Nov 09 '22 12:11

MSalters