Can I use bitwise operators instead of logical ones?

前端 未结 5 1821
青春惊慌失措
青春惊慌失措 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条回答
  •  萌比男神i
    2021-01-18 05:26

    You shouldn't. Assume you receive two values which allow you to proceed only if they are both non-zero.

    int b = foo(1); // returns 0x1
    int c = foo(2); // returns 0x2
    

    Than the following conditions result in the follows: b && c == true, while b & c == 0

    if (b && c)
    {
      // This block will be entered
    }
    
    if (b & c)
    {
      // This block won't
    }
    

提交回复
热议问题