大家好
下面通过一段代码说明有符号型与无符号型的区别
#include <iostream>
#define ZERO 0
#include <climits>
int main()
{
using namespace std;
short sam = SHRT_MAX;//SHRT_MAX为short的最大取值
unsigned short sue = sam;
cout << "sam" << sam << endl;
cout << "sue" << sue << endl;
sam = sam + 1;
sue = sue + 1;
cout << "sam" << sam << endl;
cout << "sue" << sue << endl;
sam = ZERO;
sue = ZERO;
cout << "sam" << sam << endl;
cout << "sue" << sue << endl;
sam = sam - 1;
sue = sue - 1;
cout << "sam" << sam << endl;
cout << "sue" << sue << endl;
system("pause");
return 0;
}
运行结果如下
可见,一旦超过范围,其值将为范围另一端的取值。
即对有符号型:数据从0变化至32767,32767跳变至-32768,-32768再变化至-1,-1跳变至0。
对无符号型:数据从0变化至+65535,+65535跳变至0。