我已阅读该问题的答案:Why is a char and a bool the same size in c++?并做了一个实验来确定 _Bool
的内存中分配的字节大小和一个 bool
(我知道 bool
是 _Bool
中 stdbool.h
的宏,但为了完整起见,我也使用了它)C 中的对象,以及 bool
我在 Linux Ubuntu 12.4 上实现的 C++ 对象:
对于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
因此, boolean 类型的对象,无论具体是 C 还是 C++,都在内存中占用 1 个字节(8 位),而不仅仅是 1 位。
我的问题是:
- 为什么
bool
类型的对象和_Bool
在 C 和bool
中在C++中只能存储0
的值或1
如果它们在内存中占用 1 个字节可以容纳 256 个值?
当然,他们的目的是只代表 0
的值和1
或true
和false
,但是哪个单元或宏决定它只能存储 0
或1
?
其他问题,但不是我的主要问题:
- 如果 boolean 类型的值*意外地在内存中修改为更大的值(因为它可以通过这种方式存储在内存中),会发生什么情况?
*对于意外,我的意思是:由“不可检测的手段”修改 - What are “undetectable means” and how can they change objects of a C/C++ program?或 f.e. 的不适当分配bool a; a = 25;
.
最佳答案
C 语言限制 _Bool
中可以存储的内容,即使它有能力保存除 0 和 1 之外的其他值。
C standard 第 6.3.1.2 节以下内容涉及到 _Bool
的转换:
When any scalar value is converted to
_Bool
, the result is 0 if the value compares equal to 0; otherwise, the result is 1.
C++17 standard第 7.14 节中有类似的语言:
A prvalue of arithmetic, unscoped enumeration, pointer, or pointer to member type can be converted to a prvalue of type
bool
. A zero value, null pointer value, or null member pointer value is converted to false; any other value is converted to true. For direct-initialization (11.6), a prvalue of typestd::nullptr_t
can be converted to a prvalue of typebool
; the resulting value is false.
因此,即使您尝试将其他值分配给 _Bool
该语言会将值转换为 0 或 1(对于 C)以及 true
或false
对于C++。如果您尝试通过写入 _Bool
来绕过此问题通过指向不同类型的指针,您可以调用 undefined behavior .
关于c++ - 为什么bool和_Bool在内存中占用1个字节只能存储0或1?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59863467/