Can I use bitwise operators instead of logical ones?

前端 未结 5 1687
青春惊慌失措
青春惊慌失措 2021-01-18 04:52

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

5条回答
  •  囚心锁ツ
    2021-01-18 05:21

    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.

提交回复
热议问题