yohhoyの日記

技術的メモをしていきたい日記

size_tと値-1

C/C++言語における符号無し型と負数の扱いについてメモ。値-1size_tなどの符号なし整数型*1へ変換代入する場合、同型の最大値となることが保証される。この振る舞いは符号付き整数型の内部ビット表現に依存しない*2

const size_t nmax = -1;
// nmaxはsize_t型の最大値(全ビット1)

C99 6.3.1.3/p2より引用。値-1は (変換先の型の最大値 + 1) - 1 となり、その結果は符号なし整数型の最大値に等しい。

Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type.

C++03 4.7/p2より引用。値-1は 2n を法として合同となる符号なし整数型での最小値、つまり符号なし整数型の最大値となる。

If the destination type is unsigned, the resulting value is the least unsigned integer congruent to the source integer (modulo 2n where n is the number of bits used to represent the unsigned type). [Note: In a two's complement representation, this conversion is conceptual and there is no change in the bit pattern (if there is no truncation). ]

メモ:C規格とC++規格で事実上は同じ定義となっている。C++の方が表現がスマートか(?)
関連URL

*1:C標準規格により size_t は符号なし整数型と定義される(C99 7.17/p2)。C++標準規格でも同様(C++03 18.1/p3, C++11 18.2/p6)。

*2:符号付き整数型が2の補数表現(two's complement representation)ならば、単なるビット列の読み替えに相当する。