what is a good way to create a 3-state boolean in a C-based language?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With