C++无符号整号

本文通过C++代码示例探讨了无符号整型(如short和unsignedshort)在表示范围和可能的溢出情况。C++确保了无符号类型的值不会超过范围,但对有符号整型并不提供类似保证。
摘要由CSDN通过智能技术生成

无符号整型的优点是可以增大变量能够存储的最大值,如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++并不保证符号整型超越限制(上溢或下溢)时不出错。
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值