What is the best way to have a boolean variable with three values in c ++?
Boolean values, by definition, have only 2 possible states - True or False. If you want to have a different state for "incorrect" or "not set", then you need to encapsulate the bool variable in some other data types.
The correct solution depends on what you want to do with this variable. For simple comparisons (if-else and switch), preferred enumerations (c ++ 11) should be preferred.
enum class tristate{true,false,undefined=0};
They are simple, easy to use and understand, and provide type safety compared to old enumerations. Since they are type-safe, you cannot accidentally compare them with different types of enumerations or number types, but it also means that you also cannot use bit tricks and integer tricks. If no other type is specified, the enumerated class is a numeric type that initializes to "0". this means that by assigning the value '0' to one of the enumerated values, you can make it the default state.
tristatet[7]; t[1] = tristate::true; t[2] = tristate::false; t[3] = tristate::undefined; t[4] = false; //error t[5] = 0; //error t[6] = null; //error t[0] == true; //error t[0] == tristate::true; // false t[0] == tristate::undefined; // true
Of course, you can use this in a switch statement:
switch(t[2]) { case tristate::true: foo(); break; case tristate::false: bar(); break; //t[2] was set to tristate::false case tristate::undefined : doNothing(); break; }
source share