C/C++言語における符号無し型と負数の扱いについてメモ。値-1
をsize_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). ]