Boolean true - positive 1 or negative 1?

前端 未结 11 1388
一生所求
一生所求 2020-12-31 11:05

I\'m designing a language, and trying to decide whether true should be 0x01 or 0xFF. Obviously, all non-zero values will be converted to true, but I\'m trying t

11条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-31 11:34

    Using -1 has one advantage in a weakly typed language -- if you mess up and use the bitwise and operator instead of the logical and operator, your condition will still evaluate correctly as long as one of the operands has been converted to the canonical boolean representation. This isn't true if the canonical representation is 1.

      0xffffffff & 0x00000010 == 0x00000010 (true)
      0xffffffff && 0x00000010 == 0xffffffff (true)
    

    but

      0x00000001 & 0x00000010 == 0x00000000 (false)
      0x00000001 && 0x00000010 == 0xffffffff (true)
    

提交回复
热议问题