Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have a tri-state 'boolean' in c++

Tags:

c++

boolean

What is the best way to have three value Boolean variable in c++?

I would like to have fields set to true, false or not set at all in my array.

If I declare them this way:

t[0] = true;
t[1] = false;
t[2] = NULL;

When I test the condition I get:

t[2] is false

like image 779
Snorlax Avatar asked Mar 03 '16 15:03

Snorlax


1 Answers

This should work:

t[0] = true;
t[1] = false;
t[2] = -1;

Or if you only need 3 states but perhaps would like more at some point, an enum is great:

enum STATES
{
    NULL_STATE = -1,    // you can manually specify -1 to give it a special case value
    FALSE,              // will be equal to 0
    TRUE                // will be equal to 1
};

No matter what though, 0/false is the only thing that returns false in an if() statement. -1 and true both return true.

You may want to use a switch like this to deal with 3+ states:

switch (var)    // may need to cast: (int)var
{
case 1:
case 0:
case -1:
};

Alternatively if you want to stick to an if statement block, you could do something like this:

if (var == -1)    // or (var == NULL_STATE)
{}
else if (var)     // true condition
{}
else              // false
{}
like image 106
Enigma Avatar answered Sep 28 '22 02:09

Enigma