免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 3867 | 回复: 3
打印 上一主题 下一主题

[C++] 无符号 unsigned short型的 10 ,求反后,为何会得到负数呢? [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2010-09-03 08:08 |只看该作者 |倒序浏览
无符号 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;
}

论坛徽章:
0
2 [报告]
发表于 2010-09-03 08:24 |只看该作者
运算的时候被扩展成int了

论坛徽章:
0
3 [报告]
发表于 2010-09-03 10:13 |只看该作者
谢谢,但是我还是不明白,求反,并没有与别的数运算呀。
如果是整数与双精度数运算,则整数会扩展为双精度数,
但是求反,就是对自已本身处理呀。为何也会扩展到更大的一个级别呢?

论坛徽章:
0
4 [报告]
发表于 2010-09-03 10:41 |只看该作者
谢谢,但是我还是不明白,求反,并没有与别的数运算呀。
如果是整数与双精度数运算,则整数会扩展为双精度 ...
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 ,这叫整数提升。其他类型不受此规则限制
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP