Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If statement using Bitwise AND Operators to force evaluations

I have several independent functions which return either true or false depending other conditions. When they all return true I want an action to occur, however I want all of the functions to run regardless of how many return false. If I just wanted to check all of the functions were returning true I would use:

if (func1() && func2() && func3() ){
    //Some code
}

The problem with this is that if one of the functions returns false all of the functions to the right will not execute. One method I haven't tried before is using Bitwise AND Operators (&) in the if expression, which would look like:

if (func1() & func2() & func3() ){
    //Some code
}

I have briefly tested this method and it seems to be producing the desired outcome however I could not find this method used elsewhere and I am wondering if there is any reason that this could produce a unexpected outcome?

Also is there is a good reason not to compare the results of the functions using this method?

like image 334
Oracle Avatar asked Dec 01 '25 02:12

Oracle


1 Answers

If they're just returning boolean true/false operations, then it'll work as expected:

if (true & false & true) 

would simply be "false".

But if they're turning (say) integers, then you're going to get unexpected results:

if (10 & 100 & 32)

would be

if (b1010 & b1100100 & b100000)

and evaluate to false.

like image 54
Marc B Avatar answered Dec 03 '25 17:12

Marc B



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!