布尔在内存中如何表示? [英] How is a bool represented in memory?

查看:22
本文介绍了布尔在内存中如何表示?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如已经在 文档中讨论过的,一个 bool 数据类型至少占用一个字节的内存.之前在 SO 上提出了类似的问题(How a bool类型变量是否存储在内存中?(C++)),但是这个讨论和文档似乎只讨论布尔数据类型占用的空间量,而不是实际发生的情况在内存中当我这样做时:

As already discussed in the docs, a bool data type occupies at least a byte of memory. A similar question was asked on SO before (How a bool type variable is stored in memory? (C++)), but this discussion and the documentation only seem to discuss the amount of space occupied by a boolean data type, not what actually happens in memory when I do this:

bool b = true;

那么内存中到底发生了什么?未用于存储此信息的 7 位会发生什么?标准是否为此规定了行为?

So what does actually happen in memory? What happens to the 7 bits that are not used in storing this information? Does the standard prescribe behavior for this?

它们是未定义的吗?还是 C++ 总部的某个人这样做了:

Are they undefined? Or did someone at C++ headquarters just do this:

enum bool : char 
{
  false = 0,
  true = 1
};

推荐答案

标准规定 bool 值表现为整数类型,但没有指定它们在内存中的具体表示:

Standard states that bool values behave as integral types, yet it doesn't specify their concrete representation in memory:

"bool 类型的值为 truefalse.如下所述,bool值表现为整数类型.bool 类型的值参与整数提升" ~ C++03 3.9.1 §6

"Values of type bool are either true or false. As described below, bool values behave as integral types. Values of type bool participate in integral promotions" ~ C++03 3.9.1 §6

整数类型的同义词是整数类型.整数类型的表示应使用纯二进制计数系统定义值" ~ C++03 3.9.1 §7

然而它定义了从 boolint 的整体提升:

Yet it defines the integral promotion from bool to int:

"bool 类型的右值可以转换为 int 类型的右值,false 变为零和 true 合而为一.这些转换称为积分提升." ~ C++03 4.5 §4-5

"An rvalue of type bool can be converted to an rvalue of type int, with false becoming zero and true becoming one. These conversions are called integral promotions." ~ C++03 4.5 §4-5

以及从其他类型到bool的转换:

as well as conversion from other types to bool:

零值、空指针值或空成员指针值转换为false;任何其他值转换为true." ~ C++03 4.12 §1

"A zero value, null pointer value, or null member pointer value is converted to false; any other value is converted to true." ~ C++03 4.12 §1

这篇关于布尔在内存中如何表示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆