teupoui
teupoui

Reputation: 303

Bitwise AND with function returning bool in C++

I have written a program that lists errors in a set of stuff, and returns a boolean value at the end (returning true means that no error has been found).

Here is a summary of my code :

bool checkStuff1() {/*...*/}
bool checkStuff2() {/*...*/}
// ...
bool checkStuffN() {/*...*/}

bool checkAllStuff()
{
    bool result = true;
    result &= checkStuff1();
    result &= checkStuff2();
    // ...
    result &= checkStuffN();
    return result;
}

I have confidence the value of result will be the right one at the end. However, I would like to be sure that all the functions checkStuffX() are called (because they print error messages when failing, and I would like all the error messages to be printed).

I know that if I wrote this way, it would skip all checkStuffX() after the first one failing :

result = result && checkStuffX(); // Will not call checkStuffX() if result is already false

I also know that if I wrote this way, it will call all checkStuffX() functions :

result = checkStuffX() && result; // Will always call checkStuffX() even if result is false

But I was wondering if the behaviour of the code I am using, with bitwise comparison, was determined and guaranteed by the standard ?

Or is there a risk of undefined behaviour, depending on the compiler used and its optimisations ?

Upvotes: 8

Views: 942

Answers (2)

Swift - Friday Pie
Swift - Friday Pie

Reputation: 14708

It would work, though conversion int<->bool maybe performance issue, if you have many checks. Oh, you may take advantage of function pointers and for loop, if all functions have same type.

bool  (*checks[])( void )= {checkStuff1, checkStuff2 ...  checkStuffN};

bool result = true;
for (int i = 0; i < sizeof(checks)/sizeof(checks[0]); result = checks[i++]() && result );

Code would look simpler if you can use ranged for() - like for(auto i : checks). Advantage of that if you have that procedure declared somewhere else in code, need to remove or add a step, you just modify declaration of the array (or your program can change it, effectively changing the workflow!). Downside - you can't use it with checks that have different prototypes.

Upvotes: 0

Sam Varshavchik
Sam Varshavchik

Reputation: 118435

This is perfectly fine.

Short-circuit evaluation, to which you're referring to, applies only to the && and || operators.

Upvotes: 9

Related Questions