Eg, if I write something like this
is it possible that b() doesn't get evaluated if a() returns false? What does the standard say about this?Code:if (a() && b()) {
//.....
}
Thank you
Printable View
Eg, if I write something like this
is it possible that b() doesn't get evaluated if a() returns false? What does the standard say about this?Code:if (a() && b()) {
//.....
}
Thank you
Yes, that's right. If a() returns false, everything to the right of the && won't be executed.
The answer is: b() won't get evaluated if a() returns false.
I don't know what the standard say about, but this program will tell you:
Code:#include <iostream>
using namespace std;
bool a ()
{
cout << "a\n";
return 0;
}
bool b ()
{
cout << "b\n";
return 1;
}
int main ()
{
if (a() && b());
return 0;
}
hmm I see. Thanks for the help. I was just making sure that it is the standard behaviour.
btw, then, what should I write if I want all of them to be evaluated regardless of the return values? (except making a bunch of temporary variables and recording each return values first of course)
The standard says that b() will definitely not be evaluated if a() is false. Code which actually uses this behavior is not uncommon. For instance:
Will invoke the functions A, B, C, D, in that order, as long as they return true. You can use this to do a multi-part operation in sequence, stopping if anything fails. The alternative using if-statements would be:Code:A() && B() && C() && D();
The || operator can be used in the same way but the opposite sense.Code:if(A())
{
if(B())
{
if(C())
{
D();
}
}
}
hmm I see... Thanks for the suggestions.
Note that this is GUARANTEED by the standard, and it allows things like this to work:
--Code:if (fgets(buffer, sizeof buffer, stdin) != NULL && buffer[0] != '\n') ...
// or
if (x && y / x > 7) ... // if x == 0, we can't divide by x.
// or
if (ptr != NULL && ptr->member == mymember) ...
Mats
Of course, if you have a loop header, this might not work. You could use the comma operator instead.
Code:while(a_status = a(), b_status = b(), a_status && b_status)
There is a sequence point at the comma operator, so the order of evaluation is defined here.Quote:
But couldn't those be evaluated in any order, or is that only for function parameters?
because a() and b() have side effects.Quote:
Why would you want to?
If you only want your if statement to execute if both functions return true, why waste time executing b() if a() already returned false?
hmm, I wasn't aware of that. Mind explaining it a bit?Quote:
That could be considered a problem by itself. But it depends on the exact situation.
Thanks
Well, if the primary use of the functions is their side effect, and the return value is merely a success indicator, it's mostly fine. (I'd prefer exceptions, but not everyone does, and in some environment, exceptions cannot be used.)
If the return value is more significant and the side effect is really a side effect, that's bad.