Bool (C++)

From Just Solve the File Format Problem
(Difference between revisions)
Jump to: navigation, search
(released)
 
Line 16: Line 16:
 
| uniform type  =
 
| uniform type  =
 
| conforms to    =  
 
| conforms to    =  
| released      =
+
| released      = 1983
 
| image          =  
 
| image          =  
 
| caption        =  
 
| caption        =  

Latest revision as of 07:04, 13 May 2015

File Format
Name bool (C++)
Ontology
Released 1983


bool can store one of two potential values true or false. Theoretically it can be done using a single bit of memory, however, RAM cannot be addressed by a single bit, therefore at least one byte is used most of the time. This opens the question which bit should be used to determine truth value, in C++ any bit set to 1 means that the value is true, however, when the literal constant true generates an integer value 1 (a single lowest bit being 1, the rest set to 0).

7 6 5 4 3 2 1 0 value
1 0 0 0 0 0 0 0 true
0 1 1 1 1 1 1 1 true
0 0 0 0 0 0 0 0 false
0 0 0 0 0 0 0 1 true

In bold you see the definition of these constants. When converting literal constant true to an integer type, you are guaranteed to get 1, converting false always yields 0.

However, different "true" values will not evaluate as equal when being compared.

#include <iostream>

union crazyBool
{
        unsigned char uc;
        bool b;
};

int main()
{
        crazyBool a, b;
        a.uc = 1;
        b.uc = 5;

        if(a.b == b.b)
        {
                std::cout << "==" << std::endl;
        }
        else
        {
                std::cout << "!=" << std::endl;
        }
        return 0;
}

This code will return "!=". However the following code returns "==":

        if((bool)a.uc == (bool)b.uc)
        {
                std::cout << "==" << std::endl;
        }
        else
        {
                std::cout << "!=" << std::endl;
        }

[edit] Storing in a single bit

It is possible to potentially store several bools together in less memory than if there were stored separately. This is done by placing them in a single byte, and reading their values by bit-shifting and bitwise AND operation. For example std::vector container has the specialisation for storing bool values, which does exactly that [1].

[edit] Other C++ data types of the same size

There is no other data type that can be stored in a single bit, but there are several which use a single byte.

Personal tools
Namespaces

Variants
Actions
Navigation
Toolbox