我已经阅读了以下问题的答案:Why is a char and a bool the same size in c++?,并进行了实验以确定_Bool
和bool
的内存中分配的字节大小(我知道bool
是_Bool
中stdbool.h
的宏,但出于完整性考虑,我使用了它在我的实现Linux Ubuntu 12.4上,还包括C中的对象以及C++中的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
因此, bool(boolean) 类型的对象(无论具体是C还是C++)都在内存中占据1个字节(8位),而不仅仅是1位。
我的问题是:
bool
和_Bool
类型的对象和C++中的bool
类型的对象在内存中占据1个字节(可以容纳256个值),那么它们只能存储0
或1
的值? 当然,它们的目的是仅表示
0
和1
或true
和false
的值,但是哪个单位或宏决定它只能存储0
或1
?另外,但不是我的主要问题:
*不小心是指:被“无法检测到的手段”修改-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
的转换:
C++17 standard在7.14节中具有类似的语言:
因此,即使您尝试为_Bool
分配其他值,该语言也会将C的值转换为0或1,而将C++的值转换为true
或false
。如果尝试通过使用其他类型的指针写入_Bool
来绕过此操作,则调用undefined behavior。