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.
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 &
.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With