看下面四段程序:
#include<iostream>
using namespace std;
int main()
{
short a = 0x8000;
short b = 0x7fff;
short c = a+b;
cout << "c = " << c <<endl;
return 0;
}
输出结果为:
c = -1
#include<iostream>
using namespace std;
int main()
{
unsigned short a = 0x8000;
unsigned short b = 0x7fff;
unsigned short c = a+b;
cout << "c = " << c <<endl;
return 0;
}
输出结果为:
c = 65535
#include<iostream>
using namespace std;
int main()
{
unsigned short a = 0x0001;
unsigned short b = 0x7fff;
unsigned short c = a+b;
cout << "c = " << c <<endl;
return 0;
}
输出结果为:
c = 32768
#include<iostream>
using namespace std;
int main()
{
short a = 0x0001;
short b = 0x7fff;
short c = a+b;
cout << "c = " << c <<endl;
return 0;
}
输出结果为:
c = -32768
根据以上几段程序的输出结果比较可以知道,有符号和无符号的数据类型的取值范围,以及越界后的加减法的运算结果。