无符号整型的优点是可以增大变量能够存储的最大值,如short的范围-32768到32767,则无符号的表示范围是0-65535。(当数值不会表示为负数时才应使用无符号类型,unsigned本身是unsigned int的缩写)
#include <iostream>
#include <string>
using namespace std;
#define ZERO 0;
#include <climits>
int main() {
using namespace std;
short sam=SHRT_MAX;
unsigned short sue=sam;
cout<< sam<<"|||"<< sue<<endl;
sam=sam+1;
sue=sue+1;
cout<< sam<<"|||"<< sue<<endl;
sam=ZERO;
sue=ZERO;
cout<< sam<<"|||"<< sue<<endl;
sam=sam-1;
sue=sue-1;
cout<< sam<<"|||"<< sue<<endl;
return 0;
// 输出结果:
// /Users/ppandermao/CLionProjects/c++/cmake-build-debug/c__
// 32767|||32767
// -32768|||32768
// 0|||0
// -1|||65535
//
// Process finished with exit code 0
// 可以看出,这些整形变量的行为就像里程表,如果超越了限制,其值将为范围另一端的取值。
// C++确保了无符号类型的这种行为,但c++并不保证符号整型超越限制(上溢或下溢)时不出错。
}