Bitwise operators work on bits, logical operators evaluate boolean expressions. As long as expressions return
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;
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.
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
&&, No undefined behaviour exists anymore.