官术网_书友最值得收藏!

Boolean

The standard C language doesn't define a Boolean type natively. C++, however, does, and is defined using the bool keyword. When writing in C, a Boolean can be represented using any integer type, with false typically representing 0, and true typically representing 1. As an interesting side note, some CPUs are capable of comparing a register or memory location to 0 faster than 1, meaning that on some CPUs, it's actually faster for Boolean arithmetic and branching to result in false in the typical case. 

Let's look at a bool using the following code:

#include <iostream>

int main(void)
{
auto num_bytes = sizeof(bool);
auto min = std::numeric_limits<bool>().min();
auto max = std::numeric_limits<bool>().max();

std::cout << "num bytes: " << num_bytes << '\n';
std::cout << "min value: " << min << '\n';
std::cout << "max value: " << max << '\n';
}

// > g++ scratchpad.cpp; ./a.out
// num bytes: 1
// min value: 0
// max value: 1

As shown in the preceding code, a Boolean using C++ on a 64 bit Intel CPU is 1 byte in size, and can take on a value of 0 or 1. It should be noted, for the same reasons as already identified, a Boolean could be 32-bits or even 64-bits, depending on the CPU architecture. On an Intel CPU, which is capable of supporting register sizes of 8 bits (that is, 1 byte), a Boolean only needs to be 1 byte in size.

The total size of a Boolean is important to note, with respect to storing Booleans in a file on disk. A Boolean technically only needs a single bit to store its value, but rarely (if any) CPU architectures support bit-style register and memory access, meaning a Boolean typically consumes more than a single bit, and in some cases could consume as many as 64 bits. If the size of your resulting file is important, storing a Boolean using the built-in Boolean type may not be preferred (ultimately resulting in the need for bit masking). 

主站蜘蛛池模板: 汕尾市| 安宁市| 额尔古纳市| 阳西县| 迁西县| 都江堰市| 吴江市| 清水县| 大名县| 玉山县| 百色市| 临夏县| 翁牛特旗| 龙游县| 安溪县| 德安县| 四子王旗| 高平市| 馆陶县| 仁寿县| 衡山县| 资阳市| 仁寿县| 广昌县| 尼勒克县| 华亭县| 太康县| 安乡县| 武安市| 潍坊市| 黄浦区| 曲沃县| 兰西县| 广安市| 台东市| 邹平县| 玉屏| 平舆县| 肃宁县| 永兴县| 阳春市|