Reputation: 689
I want to know if, for example, I've got this function:
bool f(...) {
//something here
return true or f(...);
}
I know it does return true
but does it return it without evaluating the other part of the statement or it does evaluate the function again?
Upvotes: 1
Views: 14583
Reputation: 29265
In this case it won't call f again because it knows the result already. Lookup "lazy evaluation" or "short circuit evaluation"
Upvotes: 1
Reputation: 67221
No It will not evalue the func() call.
LOGICAL OR evaluates 'Left to Right' and will stop when an expression returns true
you can check it anyway.did you test it?
test it with below program:
#include <iostream>
using namespace std;
bool func();
bool func2();
int main()
{
func();
}
bool func2()
{
cout <<"called me"<<endl;
return true;
}
bool func()
{
return (true ||func2());
}
it will simply execute doesnot print anything to the console.
If you mean the other part of the code in the same function above the return statement,the yes,
it will be executed even if the return staement is true at the bottom.
if you mean the recursion part,then no it will not be executed since there is true before the call in that statement.if it was return false||func()
,only then there will be recursion here.
Upvotes: 3
Reputation: 403
This will not evaluate the function, since we already know that one of the operands being or'd is true. The same thing happens with:
bool f(...) {
return false and f(...)
}
This is called Short circuit evaluation.
Upvotes: 4
Reputation: 7131
It returns true without evaluating the function. Since first true encounter in or statements guarantees rest is true, so it's useless to evaluate further.
Upvotes: 1