c++ - 为什么bool和_Bool在内存中占用1个字节只能存储0或1?

标签 c++ c memory memory-management boolean

我已阅读该问题的答案:Why is a char and a bool the same size in c++?并做了一个实验来确定 _Bool 的内存中分配的字节大小和一个 bool (我知道 bool_Boolstdbool.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 的值和1truefalse ,但是哪个单元或宏决定它只能存储 01

其他问题,但不是我的主要问题:

  • 如果 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 type std::nullptr_t can be converted to a prvalue of type bool; the resulting value is false.

因此,即使您尝试将其他值分配给 _Bool该语言会将值转换为 0 或 1(对于 C)以及 truefalse对于C++。如果您尝试通过写入 _Bool 来绕过此问题通过指向不同类型的指针,您可以调用 undefined behavior .

关于c++ - 为什么bool和_Bool在内存中占用1个字节只能存储0或1?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59863467/

相关文章:

c++ - 删除存储指向某些对象的指针的数组

c++ - 在另一个类中创建线程

c++ - 如何获取 DLL 中的函数列表(托管和非托管)?

c++ - vector<unique_ptr<T>> 在 ubuntu 中占用的内存是 vector<T> 的三倍以上

c++ - "using"定义成员函数和非成员函数时的关键字

c - 这里无法理解getchar和putchar的作用

c - 我正在使用 '->' 但输出仍在询问我是否打算使用 '->'

c - C语言中如何获取不同内存段的地址范围?

c++ - 可以在 Knuth 堆上进行碎片整理吗?

java - 在 Java 中加载 StanfordOpenNLP 模型的巨大开销?