C ++ function returning bool failed
For a C ++ function foo
:
bool foo();
and the following lines of code
bool some_bool = false;
some_bool = some_bool and foo();
I noticed that foo()
it is not called, although it may have side effects. What is this behavior called and is it compiler dependent?
This is called short circuit evaluation .
In your example some_bool
is false, so the operator some_bool && foo()
will always be false. Therefore, you never need to evaluate foo()
.
Please note that this is standard C / C ++ and is not compiler dependent , as this may lead to incorrect code that you find.
Best way to write code:
bool some_bool = false;
bool foo_result = foo();
some_bool = some_bool && foo_result;
If some_bool
already false, then foo()
no (optimization) will be called, since the returned foo()
return always returns the final result.