首页 > 解决方案 > 为什么 bool 和 _Bool 在内存中占用 1 个字节时只能存储 0 或 1?

问题描述

我已经阅读了该问题的答案:为什么 c++ 中的 char 和 bool 大小相同?并做了一个实验来确定 a_Bool和 a的内存中分配字节的大小bool(我知道这bool是 in 的宏_Boolstdbool.h但为了完整起见,我也使用了它)C 中的bool对象,以及我实现中的 C++ 中的对象Linux Ubuntu 12.4:

对于 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 

因此,布尔类型的对象,无论具体是 C 还是 C++,在内存中占用 1 个字节(8 位),而不仅仅是 1 位。

我的问题是:

当然,它们的目的是只表示0and1trueand的值false,但是哪个单元或宏决定它只能存储0or 1

另外,但不是我的主要问题:

*不小心我的意思是:由“不可检测的手段”修改 -什么是“不可检测的手段”,它们如何更改 C/C++ 程序的对象?或对 fe 的不当分配bool a; a = 25;

标签: c++cmemorymemory-managementboolean

解决方案


C 语言限制了 a 中可以存储的内容_Bool,即使它能够保存除 0 和 1 之外的其他值。

C 标准的第 6.3.1.2 节说明了以下关于转换为_Bool:

当任何标量值转换为 时_Bool,如果该值比较等于 0,则结​​果为 0;否则,结果为 1。

C++17 标准在第7.14 节中有类似的语言:

算术、无作用域枚举、指针或指向成员类型的指针的纯右值可以转换为类型的纯右值bool。将零值、空指针值或空成员指针值转换为 false;任何其他值都将转换为 true。对于直接初始化(11.6),类型的纯右值std::nullptr_t可以转换为类型的纯右值bool;结果值为假。

因此,即使您尝试为 a 分配其他值,_Bool该语言也会将该值转换为 0 或 1(对于 C 和true对于falseC++)。如果您尝试_Bool通过指向不同类型的指针写入 a 来绕过此问题,则会调用未定义的行为


推荐阅读