c++ - 为什么 bool 和 _Bool 在内存中占用 1 个字节时只能存储 0 或 1?
问题描述
我已经阅读了该问题的答案:为什么 c++ 中的 char 和 bool 大小相同?并做了一个实验来确定 a_Bool
和 a的内存中分配字节的大小bool
(我知道这bool
是 in 的宏_Bool
,stdbool.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 位。
我的问题是:
- 为什么类型
bool
和_Bool
C 和bool
C++ 中的对象只能存储 的值,0
或者1
如果它们在内存中占用 1 个字节,可以容纳 256 个值?
当然,它们的目的是只表示0
and1
或true
and的值false
,但是哪个单元或宏决定它只能存储0
or 1
?
另外,但不是我的主要问题:
- 如果布尔类型的值*意外地在内存中修改为更大的值,因为它可以以这种方式存储在内存中,会发生什么?
*不小心我的意思是:由“不可检测的手段”修改 -什么是“不可检测的手段”,它们如何更改 C/C++ 程序的对象?或对 fe 的不当分配bool a; a = 25;
。
解决方案
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
对于false
C++)。如果您尝试_Bool
通过指向不同类型的指针写入 a 来绕过此问题,则会调用未定义的行为。
推荐阅读
- python - Pandas 在列上加入 DataFrame 和 Series
- android - Android房间数据库关系问题
- python - 无法初始化语言服务器协议
- javascript - 在客户端检查时间执行
- sql - 如何设计表格以支持与默认值有很多关系?
- ios - 如何限制文本字段只能输入十进制数字?
- jquery - 如何使用 AJAX 重命名 Sharepoint META 数据中的文件名?
- python - OpenStackSDK 在特定项目下创建实例
- javascript - Firefox 无法使用 JavaScript 将焦点设置到某些 DOM 元素
- ios - 我想使用 swift 在 xcode 中创建这个滑动 UIVies,我应该使用什么?一个collecntionView或TableView?