C++ Bitwise vs Logical Operators – Can Bitwise Operators Replace Logical Ones?

bitwise-operatorsc++logical-operators

Bitwise operators work on bits, logical operators evaluate boolean expressions. As long as expressions return bool, why don't we use bitwise operators instead of logical?

In this example I use bitwise instead of logical:

#include <iostream>


int main(){

    int age;
    std::cin >> age;

    if( (age < 0) | (age > 100) ) // eg: -50: 1 | 0 = 1
        std::cout << "Invalid age!" << std::endl;

//  if( (age < 0) || (age > 100) )
//      std::cout << "Invalid age!" << std::endl;

  return 0;
}

Best Answer

One possible answer is: optimization. For example:

if ((age < 0) | (age > 100))

Let assume that age = -5, no need to evaluate (age > 100) since the first condition is satisfied (-5<0). However, the previous code will do evaluate the (age > 100) expression which is not necessary.

With:

if ((age < 0) || (age > 100))

Only the first part will be evaluated.

Note: As @Lundin mentioned in the comments, sometimes | is faster than || due to the accuracy of branching for the second option (and the problem of mis-prediction). So in cases where the other expression is so inexpensive, the | option may be faster. So the only way to know in those cases is to benchmark the code on the target platform.


The most important answer is to avoid undefined behaviors and errors:

You may imagine this code:

int* int_ptr = nullptr;
if ((int_ptr != nullptr) & (*int_ptr == 5))

This code contains undefined behaviour. However, if you replace the & with &&, No undefined behaviour exists anymore.

Related Question