Alex24 Alex24 - 1 month ago 9
C++ Question

Can I use bitwise operators instead of logical ones?

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;
}

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.


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.

Comments