One possible answer: optimization . For instance:
if ((age < 0) | (age > 100))
Suppose that age = -5
, there is no need to evaluate (age > 100)
, since the first condition is fulfilled ( -5<0
). However, the previous code will evaluate the expression (age > 100)
, which is not required.
FROM
if ((age < 0) || (age > 100))
Only the first part will be appreciated.
Note. . @Lundin mentioned in comments, sometimes |
faster than ||
due to branching accuracy for the second option (and the problem of erroneous prediction). Therefore, in cases where another expression is so inexpensive | option may be faster. So the only way to find out in these cases is to check the code on the target platform.
The most important answer is to avoid undefined behavior and errors:
You can submit this code:
int* int_ptr = nullptr; if ((int_ptr != nullptr) & (*int_ptr == 5))
This code contains undefined behavior . However, if you replace &
with &&
, No undefined behavior no longer exists.
source share