Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 855
teupoui Avatar asked Nov 24 '16 18:11

teupoui


People also ask

Can a function return a Boolean value in C?

C does not provide the bool as data type. but we can create one using enum. Here is the code : #include<stdio.

What does bitwise and return in C?

The & (bitwise AND) in C or C++ takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1. The | (bitwise OR) in C or C++ takes two numbers as operands and does OR on every bit of two numbers. The result of OR is 1 if any of the two bits is 1.

Can you use bitwise operators on Booleans?

Mixing bitwise and relational operators in the same full expression can be a sign of a logic error in the expression where a logical operator is usually the intended operator.

What is the return type of bitwise and?

The bitwise AND operator ( & ) returns a 1 in each bit position for which the corresponding bits of both operands are 1 s.


1 Answers

This is perfectly fine.

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

like image 75
Sam Varshavchik Avatar answered Oct 21 '22 03:10

Sam Varshavchik