# C++で~trueがtrueになる理由——gccの奇妙なバグと未定義動作の罠

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

> Hacker News story 49953344 · language: ja · submitted 2026-10-04
> Web version: https://zeli.app/ja/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

C++の整数昇格とブール変換を組み合わせると、~trueをboolにキャストした結果がtrueになる。さらに、boolを基底型とするenumではgccが規格に反して最下位ビットを切り捨てるため、~boolean::TRUEがFALSEになる。P4313R1のビットマスク演算提案を例に、整数昇格が避けられないこと、スコープなし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;
>
> }
>
> GCCは-Wallを付けてコンパイルすると警告を出す：
>
> test.cpp:3:10: warning: ‘~’ on an expression of type bool [-Wbool-operation]
>
> return ~x;
>
> つまり、C++がこんなことをするのは驚きだが、コンパイラの警告を有効にしている人は困らない。

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

> C++はある意味でPerlの真の精神的後継者だ。何でもかんでも表現でき、その構文は難解で、論理も同じく難解だ。もちろん、ほとんどの場合、見たままが得られるものだが、見たままが得られないと気づく瞬間が来るまでは。

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

> 標数2の任意の体では、すべての元が自分自身の負元である。だから表面的にはこれは理にかなっている、直感に反するenumのコーナーケースの挙動はさておき。

---

## Cite

- Page: https://zeli.app/ja/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
- zh: https://zeli.app/zh/story/49953344 · markdown: https://zeli.app/zh/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
