高手们分析一下C++ 中short 型变量最大值加1后没有变负值,也不知道是BUG还是它理应如此(人穷没有分啊。高手们不要生气啊)

jingzizhuo jingzizhuo 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
各位高手请帮忙分析下:
以下代码均在Microsoft Visual Studio 2005和eclipse3.2.0+CDT+MinGW中编译过
代码如下:
#include <iostream>
#include <climits>
using namespace std;

int main()
{
int n_int=INT_MAX;
short n_short=SHRT_MAX;
long n_long=LONG_MAX;
unsigned int n_unsigned_int=n_int;
unsigned short n_unsigned_short=n_short;
unsigned long n_unsigned_long=n_long;
cout << "short is : " << sizeof(short) << "bytes.\n";
cout << "short is : " << sizeof(n_short) << " bytes.\n";
cout << "n_int: " << n_int;
cout << "\t\tn_short: " << n_short;
cout << "\t\tn_long: " << n_long << endl;
cout << "n_unsigned_int: " << n_unsigned_int;
cout << "\tn_unsigned_short: " << n_unsigned_short;
cout << "\tn_unsigned_long: " << n_unsigned_long << endl;

cout << "----------------变量加1后-----------------------------\n";
cout << "n_int + 1: " << (n_int + 1);
cout << "\t\tn_short + 1: " << (n_short + 1);
cout << "\t\tn_long +1: " << (n_long + 1) << endl;

cout << "n_unsigned_int+1: "<< (n_unsigned_int + 1);
cout << "\t\tn_unsigned_short+1: " << (n_unsigned_short + 1);
cout << "\t\tn_unsigned_long+1: " << (n_unsigned_long + 1);
cout << "\n--------unsigned型变量置0然后减去1后-----------------\n";
n_unsigned_int=0;
n_unsigned_short=0;
n_unsigned_long=0;
cout << "n_unsigned_int-1: "<< (n_unsigned_int - 1);
cout << "\t\tn_unsigned_short-1: " << (n_unsigned_short - 1);
cout << "\t\tn_unsigned_long-1: " << (n_unsigned_long - 1);

return 0;
}
在Microsoft Visual Studio 2005和eclipse3.2.0+CDT+MinGW中编译后结果如下:
short is : 2bytes.
n_int: 2147483647 n_short: 32767 n_long: 2147483647
n_unsigned_int: 2147483647 n_unsigned_short: 32767 n_unsigned_long: 2147483647
----------------变量加1后----------------------------
n_int + 1: -2147483648 n_short + 1: 32768 n_long +1: -2147483648
n_unsigned_int+1: 2147483648 n_unsigned_short+1: 32768 n_unsigned_long+1: 2147483648
--------unsigned型变量置0然后减去1后-----------------
n_unsigned_int-1: 4294967295 n_unsigned_short-1: -1 n_unsigned_long-1: 4294967295

问题出现在short型变量。给short型变量取最大值32767.我用的是C++内climits自定义的最大值SHRT_MAX。即然为最大值为什么加1后,结果没有像int型变量和long变量那样变为负值呢。难道short型变量占用了更多的字结。我就用sizeof()计算发现是2Byte.就不应该还能加上去呀。
----------------
随后又让无符号的 unsigned short -1后发现,居然能变成-1值来。晕到了。请各位高手们帮忙解析一下。为什么呢
...全文
评论 15
收藏 已收藏
分享
返回顶部
jingzizhuo
C++ 语言 65,214 成员 250,514 内容