Search code examples
language-agnostictri-state-logic

Tristate values -- is there a convention?


I've been thrown a bit of a poser, and I'm not sure what the answer is.

Basically - is there a convention for what values to use in tristate data-types? Doing some googling around, it doesn't look like there is: I've seen:

  • -1 = False, 0 = Not known/undefined, +1 = True
  • 0 = False, +1 = True, +2 = Not known/undefined
  • -1 =Not known/undefined, 0 = False, +1 = True

..amongst others. I'd rather use a well-known convention if there is one. Otherwise I'll make one up :-) It may well be there is no right answer, but just thought I'd dig a bit deeper...

Edit
Found this one as well that Microsoft seem to use in recent code: -1 = true, 0 = false, 2 = not known. I assume having 2 == unknown means it removes the ambiguity over interpreting +1/-1 when just looking at the raw values in a debugger/dump/memory etc. Oddly enough, this option appeals just for this reason alone (removes chance of forgetting which variation of 1 means 'true').


Solution

  • To my knowledge, there is no convention for that.

    There isn't even a single convention for a boolean value, the most common are:

    • 0 = False, -1 = True
    • 0 = False, 1 = True

    Another common (but not universal) convention that would be relevant is the usage of -1 for undefined values.

    If you choose to use -1 for undefined, you could use 0/1 for False/True:

    • -1 = Undefined
    • 0 = False
    • 1 = True

    And naturally I have to mention that the third state should of course not be undefined/unknown, but FileNotFound. ;)