Search code examples
cbooleanstate

Three-state Boolean


What is a good way to create a three-state Boolean in a C-based language?


Solution

  • While others have offered answers, I'd like to offer a justification for the best one.

    Use integer values -1/0/1 (or really, any negative/zero/positive).

    With this scheme, there is an extremely efficient check for any subset of possible values:

    (x<0)  /*   {-1} */
    (!x)   /*    {0} */
    (x>0)  /*    {1} */
    (x<=0) /* {-1,0} */
    (x)    /* {-1,1} */
    (x>=0) /*  {0,1} */
    

    On x86, all of these will compile to a single test opcode followed by a conditional jump opcode with the appropriate conditions.

    If you want to hide the implementation, you can use predicate macros for testing each of the 6 subsets.