有符号数与无符号数的上溢与下溢问题 以8位为例:
#include<stdio.h>
int main()
{
//8位有符号的最大数
char a = 127;
printf("a = %d\n",a);
a++;
printf("a = %d\n",a);
printf("************\n");
//8位有符号的最小数
char b = -128;
printf("b = %d\n",b);
b--;
printf("b = %d\n",b);
printf("************\n");
//8位无符号数的最大数
unsigned char c = 255;
printf("c = %u\n",c);
c++;
printf("c = %u\n",c);
printf("************\n");
//8位无符号数的最小数
unsigned char d = 0;
printf("d = %u\n",d);
d--;
printf("d = %u\n",d);
printf("************\n");
unsigned char i = 255;
i+=3;
//应该打印 出2
printf("i = %d\n",i);
printf("************\n");
char j = 127;
j+=3;
//应该打印出-126
printf("j = %d\n",j);
return 0;
}
仔细来看,溢出会造成一个范围内的循环。输出结果如下:
a = 127
a = -128
************
b = -128
b = 127
************
c = 255
c = 0
************
d = 0
d = 255
************
i = 2
************
j = -126