Boolean true - positive 1 or negative 1?

前端 未结 11 1282
一生所求
一生所求 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:26

    0xff is an odd choice since it has an implicit assumption that 8 bits is your minimum storage unit. But it's not that uncommon to want to store boolean values more compactly than that.

    Perhaps you want to rephrase by thinking about whether boolean operators produce something that is just one 0 or 1 bit (which works regardless of sign extension), or is all-zeroes or all-ones (and depends on sign extension of signed two's-complement quantities to maintain all-ones at any length).

    I think your life is simpler with 0 and 1.

    0 讨论(0)
  • 2020-12-31 11:27

    The pros are none, and the cons are none, too. As long as you provide an automatic conversion from integer to boolean, it will be arbitrary, so it really doesn't matter which numbers you choose.

    On the other hand, if you didn't allow this automatic conversion you'd have a pro: you wouldn't have some entirely arbitrary rule in your language. You wouldn't have (7 - 4 - 3) == false, or 3 * 4 + 17 == "Hello", or "Hi mom!" == Complex(7, -2).

    0 讨论(0)
  • 2020-12-31 11:31

    It doesn't matter, as long as it satisfies the rules for the external representation.

    I would take a hint from C here, where false is defined absolutely as 0, and true is defined as not false. This is an important distinction, when compared to an absolute value for true. Unless you have a type that only has two states, you have to account for all values within that value type, what is true, and what is false.

    0 讨论(0)
  • 2020-12-31 11:32

    Why are you choosing that non-zero values are true? In Ada true is TRUE and false is FALSE. There is no implicit type conversion to and from BOOLEAN.

    0 讨论(0)
  • 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)
    
    0 讨论(0)
提交回复
热议问题