Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ function returning bool not executed [duplicate]

Tags:

c++

Given a C++ function foo:

bool foo();

and the following lines of code

bool some_bool = false;
some_bool = some_bool and foo();

I observed that foo() is not called although it might have side-effects. What is the name of this behavior and is it compiler-dependent?

like image 515
Elrond1337 Avatar asked Sep 17 '26 23:09

Elrond1337


1 Answers

This is called short-circuit evaluation.

In your example, some_bool is false and so the statement some_bool && foo() is always going to be false. So there is never any need to evaluate foo().

Note that this is standard C/C++ and is not compiler dependent as it can lead to unperformed code as you've discovered.

A better way of writing the code is:

bool some_bool = false;
bool foo_result = foo();
some_bool = some_bool && foo_result;
like image 149
CadentOrange Avatar answered Sep 19 '26 12:09

CadentOrange



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!