# C++ 中 true 的补码为何仍是 true？

Original title: The complement of true is true, except when it's false

> Hacker News story 49953344 · language: zh · submitted 2026-10-04
> Web version: https://zeli.app/zh/story/49953344
> About this feed: https://zeli.app/llms.txt · Agent guide: https://zeli.app/skill.md

▲ 72 · by [aw1621107](<https://news.ycombinator.com/user?id=aw1621107>) · 💬 28
[original](<https://dryperspective.github.io/posts/complement-of-true/>) · [HN discussion](<https://news.ycombinator.com/item?id=49953344>)

## Summary

最近我在研究 P4313R1 提案时，发现 C++ 位运算中一个令人费解的角落。当对 bool 类型执行按位取反操作时，由于 integral promotion 机制，true 会被提升为 int 的 1，取反后得到 -2，再转回 bool 时因非零特性又变回了 true。这意味着 static_cast<bool>(~true) 的结果竟然是 true。更复杂的是，gcc 在处理基于 bool 的 enum 时表现与 Clang 和 MSVC 不同，甚至可能触发未定义行为。这篇文章深入剖析了 C++ 标准中关于类型提升、布尔转换以及未定范围 enum 的微妙规则，揭示了这些看似无害的操作背后潜藏的逻辑陷阱和编译器差异。

## Key quote

> 这就是真相：true 的补码是 true，用 C++ 代码表达就是 static_cast<bool>(~true) 等于 true。

## HN discussion (28 comments)

### [Panzerschrek](<https://news.ycombinator.com/item?id=49978427>)

> 举个例子：
>
> bool Complement( bool x )
>
> {
>
> return ~x;
>
> }
>
> 如果用 -Wall 编译，GCC 会给出警告：
>
> test.cpp:3:10: warning: ‘~’ on an expression of type bool [-Wbool-operation]
>
> return ~x;
>
> 所以，C++ 这样做确实令人惊讶，但只要开启了编译器警告，就不会出问题。

### [rep_lodsb](<https://news.ycombinator.com/item?id=49975949>)

> 他们本该像某些其他语言（比如 Forth 和 BASIC）那样，把 true 定义为 -1（所有位都置 1）。

### [s-zeng](<https://news.ycombinator.com/item?id=49976943>)

> 在任何特征为 2 的域中，每个元素都是其自身的负数。因此，表面上看这说得通，尽管那个 enum 的边界情况行为有些反直觉。

---

## Cite

- Page: https://zeli.app/zh/story/49953344
- Date: 2026-10-04
- Source: dryperspective.github.io (https://dryperspective.github.io/posts/complement-of-true/)
- Hacker News: https://news.ycombinator.com/item?id=49953344

## Other languages

- en: https://zeli.app/story/49953344 · markdown: https://zeli.app/story/49953344.md
- ja: https://zeli.app/ja/story/49953344 · markdown: https://zeli.app/ja/story/49953344.md
- ko: https://zeli.app/ko/story/49953344 · markdown: https://zeli.app/ko/story/49953344.md
- de: https://zeli.app/de/story/49953344 · markdown: https://zeli.app/de/story/49953344.md
- es: https://zeli.app/es/story/49953344 · markdown: https://zeli.app/es/story/49953344.md
- ru: https://zeli.app/ru/story/49953344 · markdown: https://zeli.app/ru/story/49953344.md
