次の例を検討してください。
#include <stdio.h>
int main(void)
{
unsigned char a = 15; /* one byte */
unsigned short b = 15; /* two bytes */
unsigned int c = 15; /* four bytes */
long x = -a; /* eight bytes */
printf("%ld\n", x);
x = -b;
printf("%ld\n", x);
x = -c;
printf("%ld\n", x);
return 0;
}
コンパイルするには、GCC 4.4.7 を使用しています (警告は表示されませんでした)。
gcc -g -std=c99 -pedantic-errors -Wall -W check.c
私の結果は次のとおりです。
-15
-15
4294967281
問題は、 と の両方unsigned char
の値が (signed)にunsigned short
正しく「伝播」され、そうでないのはなぜですか? これに関する参照またはルールはありますか?long
unsigned int
gdb
それに応じて(単語はリトルエンディアン順です)からの結果は次のとおりです。
(gdb) x/2w &x
0x7fffffffe168: 11111111111111111111111111110001 11111111111111111111111111111111
(gdb) x/2w &x
0x7fffffffe168: 11111111111111111111111111110001 00000000000000000000000000000000