# 布尔数据类型

**布尔数据类型**是一种恰好有两个值——true 和 false——的数据类型，用于表示程序中的逻辑条件。[ECMAScript](https://www.edgepedia.org/zh/ecmascript) 规范将其布尔类型定义为“一种有两个值、称为 true 和 false 的逻辑实体”<sup>[1](https://tc39.es/ecma262/2024/multipage/ecmascript-data-types-and-values.html)</sup>；《Java 语言规范》对 `boolean` 也作同样表述：“恰好两个值：`true` 和 `false`”<sup>[2](https://docs.oracle.com/javase/specs/jls/se24/html/jls-4.html)</sup>。除这一共同定义外，各语言在布尔值如何存储、其他值如何转换为布尔值，甚至它究竟是不是一种独立类型上，差异很大：C++ 将 `bool` 归入整型<sup>[3](https://timsong-cpp.github.io/cppwp/std11/basic.fundamental)</sup>，[Python](https://www.edgepedia.org/zh/python-programming-language) 让 `bool` 成为 `int` 的子类型<sup>[4](https://peps.python.org/pep-0285/)</sup>，Rust 则保证精确的字节级表示<sup>[5](https://doc.rust-lang.org/stable/reference/types/boolean.html)</sup>。

| 关键事实 | 细节 |
|---|---|
| 定义 | 在 ECMAScript、Java、C++ 和 Rust 中同样恰好有两个值：true 和 false<sup>[1](https://tc39.es/ecma262/2024/multipage/ecmascript-data-types-and-values.html)</sup><sup> • </sup><sup>[2](https://docs.oracle.com/javase/specs/jls/se24/html/jls-4.html)</sup> |
| 内存大小 | Rust 和 Lean 各用一个字节存储 bool（0x00 或 0x01）；压缩位数组每个元素存储一位，内存用量为每元素一字节时的八分之一<sup>[5](https://doc.rust-lang.org/stable/reference/types/boolean.html)</sup><sup> • </sup><sup>[6](https://lean-lang.org/doc/reference/latest/Basic-Types/Booleans/)</sup><sup> • </sup><sup>[7](https://stl.boost.org/bit_vector.html)</sup> |
| C 的姗姗来迟 | C 直到 C9X 才加入 `_Bool` 作为可保存 0 和 1 的无符号整数类型，在此之前 C 没有内置布尔类型；程序使用整数或各项目自定义的 typedef<sup>[8](https://open-std.org/jtc1/sc22/wg14/www/docs/n815.htm)</sup> |
| Python 的 bool | 是 `int` 的子类型，`False` 和 `True` 在大多数方面表现得像 0 和 1<sup>[4](https://peps.python.org/pep-0285/)</sup> |
| JavaScript 假值集合 | `undefined`、`null`、`0`、`-0`、`0n`、`NaN` 和空字符串会强制转换为 false；其他数字则变为 true<sup>[9](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean)</sup> |
| PHP 的假值字符串 | PHP 将字符串 `"0"` 视为 false<sup>[10](https://www.php.net/language.types.boolean)</sup> |
| 近期变化 | Python 3.12 弃用了对 bool 使用 `~`（`~True` 为 -2）<sup>[11](https://docs.python.org/3/whatsnew/3.12.html)</sup> |

## 历史

该类型得名于[乔治·布尔](https://www.edgepedia.org/zh/george-boole)（George Boole，1815—1864）的代数。布尔在 1850 年前后观察到，把逻辑值真（TRUE）和假（FALSE）编码为二进制值 1 和 0，他就能构造出一种刻画命题逻辑性质的代数<sup>[12](https://csapp.cs.cmu.edu/3e/waside/waside-boolean.pdf)</sup>。用现代形式化术语说，[布尔代数](https://www.edgepedia.org/zh/boolean-algebra)由一个载体集合以及五个运算组成：顶常量、底常量、否定、合取和析取，并满足一组固定公理模式<sup>[13](https://www.ps.uni-saarland.de/courses/cl2-ws14/bl.pdf)</sup>。

**早期 C 没有它也能活。** C9X 标准委员会关于 `_Bool` 的提案记载，在标准化之前，许多 C 程序用普通整数类型保存 1 或 0 来表示布尔真或假，或者通过 typedef、枚举或预处理器宏定义自己的布尔类型，导致程序之间出现行为差异<sup>[8](https://open-std.org/jtc1/sc22/wg14/www/docs/n815.htm)</sup>。委员会标准化了一种内置类型，定义为能够表示值 0 和 1 的无符号整数类型；选择内置类型是因为它在语言层面更干净：它让翻译器直接了解该类型，从而可采用一致的提升规则，并可能带来新的优化机会<sup>[8](https://open-std.org/jtc1/sc22/wg14/www/docs/n815.htm)</sup>。只有包含 `<stdbool.h>` 头文件后，常规名称 `bool`、`true` 和 `false` 才可用<sup>[8](https://open-std.org/jtc1/sc22/wg14/www/docs/n815.htm)</sup>。

C++ 走了另一条路：其标准将 `bool` 归入整型，与 `char`、`char16_t`、`char32_t`、`wchar_t` 以及有符号和无符号整数类型并列，同时指出不存在有符号、无符号、短或长的 bool 类型<sup>[3](https://timsong-cpp.github.io/cppwp/std11/basic.fundamental)</sup>。

Python 的 `bool` 随 PEP 285 到来；该提案提出一种内置类型，带有两个常量 `False` 和 `True`，作为 `int` 的直接子类型，其值在大多数方面表现得像 0 和 1<sup>[4](https://peps.python.org/pep-0285/)</sup>。[吉多·范罗苏姆](https://www.edgepedia.org/zh/guido-van-rossum)（Guido van Rossum）的回顾指出，它正式引入于 Python 2.3，但 `bool`、`True` 和 `False` 也出现在缺陷修复版本 Python 2.2.1 中<sup>[14](https://gvanrossum.github.io/python-history/the-history-of-bool-true-and-false.html)</sup>。PEP 285 改变了所有概念上返回布尔结果的内置运算，例如比较、`not` 和 `isinstance()`，让它们返回 `False` 或 `True`，而不是 0 或 1<sup>[4](https://peps.python.org/pep-0285/)</sup>。

## 内存中的表示

一个布尔值只携带一位信息，但 Rust 和 Lean 却各为它花费整整一个字节<sup>[5](https://doc.rust-lang.org/stable/reference/types/boolean.html)</sup><sup> • </sup><sup>[6](https://lean-lang.org/doc/reference/latest/Basic-Types/Booleans/)</sup>。Rust 使表示精确：值 `false` 的位模式为 `0x00`，`true` 为 `0x01`；布尔类型的对象若持有任何其他位模式，即属未定义行为<sup>[5](https://doc.rust-lang.org/stable/reference/types/boolean.html)</sup>。Rust 还保证 `bool` 的那一个字节始终已初始化，因此 `transmute::<bool, u8>(...)` 总是安全的；反过来则并不总是安全，因为某些位模式是非法布尔值<sup>[5](https://doc.rust-lang.org/stable/reference/types/boolean.html)</sup>。Lean 同样将 `Bool` 表示为枚举归纳类型，在编译后的代码中占一个字节，只携带一位运行时信息<sup>[6](https://lean-lang.org/doc/reference/latest/Basic-Types/Booleans/)</sup>。

**把位打包在一起。** 对于布尔值数组，每元素一字节的开销可以挽回。根据其文档，SGI STL 要求 vector 的每个元素至少占一个字节，而 `bit_vector` 的每个元素只需一位。<sup>[7](https://stl.boost.org/bit_vector.html)</sup> 在标准 C++ 中，`std::vector<bool>` 以何种方式变得节省空间，以及它究竟是否被优化，均由实现定义；一种可能的优化是合并元素，使每个元素占一位而不是 `sizeof(bool)` 个字节<sup>[15](https://cppreference.com/cpp/container/vector_bool)</sup>。当大小在编译期已知时，可以使用 `std::bitset`，它提供更丰富的成员函数集合<sup>[15](https://cppreference.com/cpp/container/vector_bool)</sup>。位打包设计一直有争议：一份 2007 年的 ISO C++ 委员会文件记载，原则上同意在下一版标准中弃用而非移除 `vector<bool>`，并提供替代方案<sup>[16](https://www9.open-std.org/JTC1/SC22/WG21/docs/papers/2007/n2204.html)</sup>。一项实验性 ACM 研究比较了 `std::vector<bool>`、Boost 的 `boost::dynamic_bitset`、Qt 的 `QBitArray` 和 BitMagic 的 `bm::bvector`，还把 `std::vector<char>` 作为替代方案纳入，测量了内存使用和处理时间<sup>[17](https://dl.acm.org/doi/10.1145/1899503.1899530)</sup>。

## 运算与语义

**短路求值与及早求值。** Lean 明确记录了这一区别：其 `cond`、`and` 和 `or` 函数是短路的，使用 `macro_inline` 属性定义，因此 `false && BIG_EXPENSIVE_COMPUTATION` 无需在返回 `false` 之前执行那个昂贵表达式<sup>[6](https://lean-lang.org/doc/reference/latest/Basic-Types/Booleans/)</sup>。

**布尔值的按位运算。** 布尔代数可扩展到固定长度 w 的位向量：将每个运算逐元素施加到操作数的对应位上；对于 w = 4，a = [0110]、b = [1100]，运算 `&`、`|`、`^` 和 `~` 按位计算<sup>[12](https://csapp.cs.cmu.edu/3e/waside/waside-boolean.pdf)</sup>。在 Python 的单个布尔值上，作用于两个 bool 的二元运算符 `&`、`|` 和 `^` 返回 bool，并且行为与其逻辑等价物相同；在 `~` 被弃用时，它们被保留<sup>[18](https://github.com/python/cpython/issues/103487)</sup>。这次弃用恰恰是因为按位取反在数值类型上并非逻辑否定：在 Python 3.14 之前，`~True == -2`，所以 `bool(~True)` 为 `True`，因为 bool 继承自 int，而将 True 的各位（0000...0001）取反得到 1111...1110<sup>[18](https://github.com/python/cpython/issues/103487)</sup>。

在 C 中，降级为 `_Bool` 遵循这样的规则：若值等于 0，结果为 0；否则为 1<sup>[8](https://open-std.org/jtc1/sc22/wg14/www/docs/n815.htm)</sup>。

## 真值与强制转换

语言可分为两类：几乎任何东西都转换为布尔值的，以及完全拒绝转换的。

**JavaScript** 定义了一个假值集合：`undefined`、`null`、`0`、`-0`、`0n`、`NaN` 和空字符串会转换为 `false`，而其他数字会转换为 `true`<sup>[9](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean)</sup>。存在一个历史遗留例外：`document.all` 用作布尔值时返回 `false`，尽管它是一个对象<sup>[9](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean)</sup>。真值与宽松相等也并不一致：`NaN`、`undefined` 和 `null` 是假值，但与 `false` 宽松相等不成立<sup>[9](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean)</sup>。在宽松相等中，如果一个操作数是布尔值而另一个不是，则布尔值会转换为数字，`true` 转为 1，`false` 转为 0；MDN 推荐严格相等，因为它更易预测，且由于不发生强制转换，可能更快<sup>[19](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Equality_comparisons_and_sameness)</sup>。

**PHP** 将空字符串和字符串 `"0"` 视为 false<sup>[10](https://www.php.net/language.types.boolean)</sup>。其他所有值都被视为 `true`，包括资源和 `NAN`，而 `-1` 像任何其他非零数字一样为真<sup>[10](https://www.php.net/language.types.boolean)</sup>。PHP 的官方比较表确认，在宽松相等下 `"0"` 与 `false` 比较相等<sup>[20](https://www.php.net/manual/en/types.comparisons.php)</sup>。

**Python** 在添加该类型时保留了其宽容传统。PEP 285 明确不改变这一事实：几乎所有对象类型都可以用作真值；在 if 语句中，空列表为假，非空列表为真<sup>[4](https://peps.python.org/pep-0285/)</sup>。Python 2.3 文档补充说，加入布尔值并非为了严格类型检查；并且 Python 不像 Pascal 这样非常严格的语言，不会要求 if 语句的表达式求值为布尔结果<sup>[21](https://docs.python.org/2.3/whatsnew/section-bool.html)</sup>。

**Java** 拒绝隐式转换。Java 不会把整数或浮点表达式隐式转换为 `boolean`；诸如 `x!=0` 的比较会产生一个 `boolean` 值，这遵循了 C 的惯例：任何非零值都为真<sup>[2](https://docs.oracle.com/javase/specs/jls/se24/html/jls-4.html)</sup>。`boolean` 值只能强制转换为 `boolean`、`Boolean` 或 `Object`；不允许对 `boolean` 类型进行其他强制转换<sup>[2](https://docs.oracle.com/javase/specs/jls/se24/html/jls-4.html)</sup>。

## 用数字说话

内存算术很直接：每个布尔值一字节，对比压缩表示中每元素一位，是八倍差异，SGI 文档将其表述为每元素一字节对每元素一位之比<sup>[7](https://stl.boost.org/bit_vector.html)</sup>。

**实测扫描性能**取决于数据密度。在一项位集扫描的工程基准测试中，在稠密扫描中，AVX2/AVX-512 的速度仅为逐位扫描的约 1.40 倍到 1.45 倍；而在稀疏晚命中扫描中，从逐位扫描改为分块 `countr_zero` 扫描带来了约 73 倍到 74 倍的加速<sup>[22](https://swarnimarun.com/posts/bitsets-in-practice-cache-masks-and-simd)</sup>。测得的稠密扫描时间为逐位 242.52 ns，AVX-512 为 166.93 ns；采用分块和 SIMD 策略后，稀疏晚命中扫描从 1,855,886.53 ns 降至约 24,930 到 25,498 ns<sup>[22](https://swarnimarun.com/posts/bitsets-in-practice-cache-masks-and-simd)</sup>。同一来源建议：对于最多 64 位的小型固定标志，使用整数掩码；对于中型编译期集合，使用 `std::bitset`；对于大型稠密集合，使用分块的 `uint64_t` 字位集；对于大型稀疏集合，使用 Roaring 或压缩位图<sup>[22](https://swarnimarun.com/posts/bitsets-in-practice-cache-masks-and-simd)</sup>。

## 近期发展

**Python 3.12** 弃用了布尔类型的按位取反；Python 3.14 将其视为错误。在此变更之前，`~True` 和 `~False` 会产生令人惊讶的结果 -2 和 -1，发布说明指示程序员使用 `not x` 进行逻辑否定<sup>[11](https://docs.python.org/3/whatsnew/3.12.html)</sup>。另一项 3.12 行为变更于 2024 年浮现：在 `foo and 1 or 2` 表达式中，左操作数的布尔转换在 3.12 中可能被求值两次，而 3.11 只调用一次 `Foo.__bool__`<sup>[23](https://github.com/python/cpython/issues/124285)</sup>。

**Python 3.13** 增加了 `typing.TypeIs` 类型收窄标注<sup>[24](https://www.python.org/downloads/release/python-3130/)</sup>。引入它的 PEP 742 允许在条件语句的 `if` 和 `else` 两个分支中都进行收窄，这一点不同于现有的 `typing.TypeGuard`；收窄函数必须返回 `bool` 值，类型检查器应验证所有返回路径都返回 `bool`<sup>[25](https://peps.pythonlang.net/pep-0742/)</sup>。同一 PEP 在附带说明 Python 类型系统时指出，`bool` 是 `int` 的子类型<sup>[25](https://peps.pythonlang.net/pep-0742/)</sup>。

**Rust** 在当前参考中记录了其 bool 保证：0x00 和 0x01 位模式、任何其他模式均属未定义行为，以及将 bool 转换为 u8 的健全性<sup>[5](https://doc.rust-lang.org/stable/reference/types/boolean.html)</sup>。

## References

1. [ECMAScript® 2024 Language Specification, tc39.es](https://tc39.es/ecma262/2024/multipage/ecmascript-data-types-and-values.html)
2. [Chapter 4. Types, Values, and Variables, Java Language Specification SE 24, Oracle](https://docs.oracle.com/javase/specs/jls/se24/html/jls-4.html)
3. [C++ standard draft, basic.fundamental](https://timsong-cpp.github.io/cppwp/std11/basic.fundamental)
4. [PEP 285 – Adding a bool type, Python Software Foundation](https://peps.python.org/pep-0285/)
5. [Boolean type, The Rust Reference](https://doc.rust-lang.org/stable/reference/types/boolean.html)
6. [Booleans, The Lean Language Reference](https://lean-lang.org/doc/reference/latest/Basic-Types/Booleans/)
7. [bit_vector, SGI STL reference](https://stl.boost.org/bit_vector.html)
8. [C9X Boolean Type, WG14 proposal N815](https://open-std.org/jtc1/sc22/wg14/www/docs/n815.htm)
9. [Boolean, JavaScript, MDN Web Docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean)
10. [PHP: Booleans, Manual](https://www.php.net/language.types.boolean)
11. [What's New In Python 3.12, Python documentation](https://docs.python.org/3/whatsnew/3.12.html)
12. [CS:APP Web Aside DATA:BOOL: More on Boolean Algebra and Boolean Rings, Carnegie Mellon University](https://csapp.cs.cmu.edu/3e/waside/waside-boolean.pdf)
13. [Boolean Logic, Saarland University course notes](https://www.ps.uni-saarland.de/courses/cl2-ws14/bl.pdf)
14. [The history of bool, True and False, The History of Python, Guido van Rossum](https://gvanrossum.github.io/python-history/the-history-of-bool-true-and-false.html)
15. [std::vector<bool>, cppreference.com](https://cppreference.com/cpp/container/vector_bool)
16. [n2204: A Specification to deprecate vector<bool>, ISO C++ committee](https://www9.open-std.org/JTC1/SC22/WG21/docs/papers/2007/n2204.html)
17. [Performance of C++ bit-vector implementations, ACM](https://dl.acm.org/doi/10.1145/1899503.1899530)
18. [gh-82012: Deprecate bitwise inversion (~) of bool, CPython issue tracker](https://github.com/python/cpython/issues/103487)
19. [Equality comparisons and sameness, MDN Web Docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Equality_comparisons_and_sameness)
20. [PHP: PHP type comparison tables, Manual](https://www.php.net/manual/en/types.comparisons.php)
21. [PEP 285: A Boolean Type, What's New in Python 2.3](https://docs.python.org/2.3/whatsnew/section-bool.html)
22. [Bitsets in Practice: Cache Lines, Masks, and SIMD Tradeoffs](https://swarnimarun.com/posts/bitsets-in-practice-cache-masks-and-simd)
23. [Behavior change for `foo and 1 or 2` in Python 3.12, CPython issue tracker](https://github.com/python/cpython/issues/124285)
24. [Python Release Python 3.13.0](https://www.python.org/downloads/release/python-3130/)
25. [PEP 742 – Narrowing types with TypeIs](https://peps.pythonlang.net/pep-0742/)

---
*Initially written Sep 17, 2026 · Reviewed: Sep 30, 2026; Oct 15, 2026 · Edited: Sep 30, 2026; Oct 15, 2026 · Last review: Oct 15, 2026*

Topic: 技术与人造世界 › 计算技术与数字系统 › 软件与编程 › Programming languages › Programming language concepts

Copyright 2026 Edgepedia

License: Edgepedia Community License 1.0, https://www.edgepedia.org/edgepedia/license

Source: https://www.edgepedia.org/zh/boolean-data-type

English original: https://www.edgepedia.org/boolean-data-type
