Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

3-State Boolean?

Tags:

c

boolean

state

what is a good way to create a 3-state boolean in a C-based language?

like image 945
Chunky Chunk Avatar asked Jan 12 '11 06:01

Chunky Chunk


1 Answers

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.

like image 135
R.. GitHub STOP HELPING ICE Avatar answered Nov 03 '22 00:11

R.. GitHub STOP HELPING ICE