我已经阅读了以下问题的答案:Why is a char and a bool the same size in c++?,并进行了实验以确定_Boolbool的内存中分配的字节大小(我知道bool_Boolstdbool.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位。

我的问题是:
  • 为什么如果C语言中的bool_Bool类型的对象和C++中的bool类型的对象在内存中占据1个字节(可以容纳256个值),那么它们只能存储01的值?

  • 当然,它们的目的是仅表示01truefalse的值,但是哪个单位或宏决定它只能存储01

    另外,但不是我的主要问题:
  • 如果将 bool(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的转换:



    C++17 standard在7.14节中具有类似的语言:



    因此,即使您尝试为_Bool分配其他值,该语言也会将C的值转换为0或1,而将C++的值转换为truefalse。如果尝试通过使用其他类型的指针写入_Bool来绕过此操作,则调用undefined behavior

    10-06 05:25
    查看更多