我想到了C 和C++中_Bool
/ bool
( ) 的类型。stdbool.h
bool
我们使用布尔类型来声明对象,这些对象只能保存 0 或 1 的值。例如:
_Bool bin = 1;
或者
bool bin = 1;
(注:是头文件内部的bool
宏。)_Bool
stdbool.h
在 C 中,
或者
bool bin = 1;
在 C++ 中。
但是布尔类型真的有效吗_Bool
?bool
我做了一个测试来确定内存中每个对象的大小:
对于 C:
#include <stdio.h>
#include <stdbool.h> // for "bool" macro.
int main()
{
_Bool bin1 = 1;
bool bin2 = 1; // just for the sake of completeness; bool is a macro for _Bool.
printf("the size of bin1 in bytes is: %lu \n",(sizeof(bin1)));
printf("the size of bin2 in bytes is: %lu \n",(sizeof(bin2)));
return 0;
}
输出:
the size of bin1 in bytes is: 1
the size of bin2 in bytes is: 1
对于 C++:
#include <iostream>
int main()
{
bool bin = 1;
std::cout << "the size of bin in bytes is: " << sizeof(bin);
return 0;
}
输出:
the size of bin in bytes is: 1
因此,布尔类型的对象确实存储在内存中的 1 个字节(8 位)内,而不仅仅是一个 1 位,因为它通常只需要。
这里讨论的原因是:为什么 char 和 bool 在 c++ 中的大小相同?. 这不是我的问题。
我的问题是:
为什么我们在 C 和C++ 中使用
_Bool
/bool
( ) 类型,如果它们不提供内存存储的好处,因为它专门假装使用这些类型?stdbool.h
bool
为什么我不能只使用
int8_t
or的类型char
(假设char
在具体实现中包含 8 位(通常是这种情况))呢?
是否只是为了给代码读者提供明显的印象,即各个对象仅用于0
或1
/true
或false
目的?
非常感谢您的参与。