How to implement Short-Circuit evaluation in user-defined functions?
Asked Answered
N

3

6

Some operators such as && and || perform short-circuit evaluation. Also, when a function is called with arguments, all arguments are constructed before calling the function.

For instance, take the following three functions

bool f1();
bool f2();
bool f3(bool, bool);

if I call

if( f3(f2(),f1()) )//Do something

Then the return value of both f2 and f1 are evaluated before f3 is called. But, if I had used (the regular) operator|| instead of f3, than the code above would be equivalent to

if( f2()||f1() )//Do something

and f1 won't be evaluated if f2 evaluates to true.

My question is: is it possible to have f3 (a user defined function taking two booleans) behave the same way? If not, what makes the operator|| so special?

Norine answered 24/2, 2012 at 0:54 Comment(1)
Might be possible if you inline it... otherwise, absolutely not.Penney
D
2

Not if f3() takes the values of the result of the functions.

But if it takes the address of the functions (or more generically treats its input as functors) rather than the results then f3() can decide if it needs to call the function.

template<typename F1, typename F2>
bool f3(F1 const& f1, F2 const& f2)
{
    return f1() || f2();
}

bool f1();
bool f2();

int main()
{
    f3(&f1, &f2);
}
Demimonde answered 24/2, 2012 at 1:12 Comment(0)
R
0

Your premise is incorrect. Overloaded operator|| and operator&& always evaluate both their arguments; there is no short-circuiting.

See Item 7 of More Effective C++ for a discussion on this.

Richela answered 24/2, 2012 at 1:0 Comment(2)
I know they do. I'm not talking about overloaded operator|| I'm talking about the default operator||. I'm saying: operator|| takes 2 arguments but uses short circuiting, is it possible to have the same effect on a user defined function of 2 arguments?Norine
@BruceConnor: Ah ok. In that case, the answer is: operator|| and operator&& on primitives are special because the standard says so. I don't think there's a way to emulate this with arbitrary functions.Richela
G
0

You can't compare || operator and functions like that. || is logical operator and it checks given values, if left operand evaluated to false, then it's no need to check right one.

In case of functions, any value that f1() or f2() return is valid for f3(). There is no way to enable "logical operand" feature for function parameters, even if they take bool parameters.

Gamp answered 24/2, 2012 at 1:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.