Bitwise '&' operator

前端 未结 6 993
慢半拍i
慢半拍i 2020-11-28 14:43

I am lacking some basic understanding in bitwise \'&\' operator.

5 = 101
4 = 100

So why the output of the below if conditi

6条回答
  •  南笙
    南笙 (楼主)
    2020-11-28 15:08

    5 is 101.

    4 is 100.

    5 & 4 is not 0:

    101 
    100 &
    ↓↓↓
    100
    

    Problem solved ✓


    Clarification:

    In C, every non-zero value satisfies the if condition. Meaning, if you write:

    if (-5) {
      if (100) {
         // reachable code
      }
    }
    

    Whereas:

    if (0) {
      destroyTheWorld(); // we are safe
    }
    

提交回复
热议问题