考虑以下示例:
#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
和unsigned short
值都正确地“传播”到 (signed) long
,而unsigned int
不是?对此有什么参考或规则吗?
以下是相应的gdb
(单词按小端顺序)的结果:
(gdb) x/2w &x
0x7fffffffe168: 11111111111111111111111111110001 11111111111111111111111111111111
(gdb) x/2w &x
0x7fffffffe168: 11111111111111111111111111110001 00000000000000000000000000000000