Bool (C++)

From Just Solve the File Format Problem
(Difference between revisions)
Jump to: navigation, search
(Created page with "{{FormatInfo | name = bool (C++) | formattype = electronic | subcat = Data types | subcat2 = C++ data types | subcat3 = | subcat4 =...")
 
(oops)
Line 38: Line 38:
 
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.
 
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 evaluate as equal when being compared.
+
However, different "true" values will '''not''' evaluate as equal when being compared.
 
<pre>#include <iostream>
 
<pre>#include <iostream>
  

Revision as of 07:21, 11 May 2015

File Format
Name bool (C++)
Ontology


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 "!="

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].

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