+ -
当前位置:首页 → 问答吧 → 无符号 unsigned short型的 10 ,求反后,为何会得到负数呢?

无符号 unsigned short型的 10 ,求反后,为何会得到负数呢?

时间:2010-09-03

来源:互联网

无符号 unsigned short型的 10 ,求反后,为何会得到负数呢?

以下代码,输出结果为下列内容,我不明白,unsigned short 型的10,本身就是无符号数呀,对它取反后,为何值是-11呢?

short:-11
ushort:-11
int-11
uint4294967285

代码如下:
#include "stdafx.h"
#include <iostream>
using namespace std;

int main(int argc, _TCHAR* argv[])
{
        int i;
        cout << "-----------------" << endl;
        //int a=10;
        short a=10;
        unsigned short b=10;
        int c=10;
        unsigned int d=10;

        cout << "short:" << ~a << endl;
        cout << "ushort:" << ~b << endl;
        cout << "int" << ~c << endl;
        cout << "uint" << ~d << endl;
        //int c=10;
        cin >> i;
        return 0;
}

作者: go_hao   发布时间: 2010-09-03

运算的时候被扩展成int了

作者: davelv   发布时间: 2010-09-03

谢谢,但是我还是不明白,求反,并没有与别的数运算呀。
如果是整数与双精度数运算,则整数会扩展为双精度数,
但是求反,就是对自已本身处理呀。为何也会扩展到更大的一个级别呢?

作者: go_hao   发布时间: 2010-09-03



QUOTE:
谢谢,但是我还是不明白,求反,并没有与别的数运算呀。
如果是整数与双精度数运算,则整数会扩展为双精度 ...
go_hao 发表于 2010-09-03 10:13



ISO C中规定(C++不太清楚,也应该有这个规定) 在 conversions一节说了
If an int can represent all values of the original type, the value is converted to an int;
otherwise, it is converted to an unsigned int. These are called the integer
promotions.4 All other types are unchanged by the integer promotions.

这就是说如果int可以代表表达式中出现的全部类型(包括char,short,int),那么值就转化为int,否则就转化为unsigned int ,这叫整数提升。其他类型不受此规则限制

作者: davelv   发布时间: 2010-09-03

相关阅读 更多