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?

+3


source to share


2 answers


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;

      

+5


source


If some_bool

already false, then foo()

no (optimization) will be called, since the returned foo()

return always returns the final result.



+2


source







All Articles