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 ?
C does not provide the bool as data type. but we can create one using enum. Here is the code : #include<stdio.
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.
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.
The bitwise AND operator ( & ) returns a 1 in each bit position for which the corresponding bits of both operands are 1 s.
This is perfectly fine.
Short-circuit evaluation, to which you're referring to, applies only to the &&
and ||
operators.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With