有符号和无符号整型数据溢出问题

无符号数都有“unsigned”标志,如果没有“unsigned”标志,则程序默认该数为有符号数“signed”。
无符号数可正可负 ,有符号数一定为正。由于有符号与无符号数所占用的字节数相同,因此无符号数所允许的最大值比有符号数的大一倍。如 ,无符号短整型数的数值范围是0到65535,而有符号短整型数的范围是-32768到32767.

1.无符号整数溢出问题:

int main()
{
	 unsigned short int b=0;
     b=65535;
	 cout<<"b before is:"<<b<<endl;
	 cout<<"b after is:"<<++b<<endl;
	return 0;
}

结果:


分析:b为最大值65535时,自增1后,满足溢出条件 ,此时b值为0.


1.有符号整数溢出问题:

int main()
{
	 short int a=0;
         a=32767;
	 cout<<"a before is:"<<a<<endl;
	 cout<<"a after is:"<<++a<<endl;
	 cout<<"a after is:"<<++a<<endl;
	return 0;
}
结果:


分析:a为最大值32767时,自增1后,满足溢出条件 ,此时b值为-32768.

posted @ 2015-08-11 15:52  稻香鱼  阅读(622)  评论(0)    收藏  举报