Malabarba
Malabarba

Reputation: 4543

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

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?

Upvotes: 6

Views: 1089

Answers (3)

Sergej Kravcenko
Sergej Kravcenko

Reputation: 141

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.

Upvotes: 0

Loki Astari
Loki Astari

Reputation: 264381

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);
}

Upvotes: 2

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272477

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.

Upvotes: 0

Related Questions