c++ int,unsigned int混合表达式类型转换

C++类型转换
本文通过一个C++示例代码展示了int类型与unsigned int类型在进行混合运算时的自动转换过程。当两者进行比较或者运算时,int类型的变量会被转换为unsigned int类型。这可能会导致一些预期之外的结果。

测试代码:

#include<cstdio>
#include<iostream>
using namespace std;
int main() {
    unsigned int a = 3;
    int b=2,c=1;
    if(b<c-a) cout<<"int transform to unsigned int"<<endl;
    cout<<b<<" "<<c-a<<endl;;
    cout<<a*-1<<endl;
    long long d = 5;
    cout<<a-d<<" "<<sizeof(a-d)<<endl;
    return 0;
}

运行结果:

int transform to unsigned int
2 4294967294
4294967293
-2 8

 

int和unsigned int的混合表达式,计算时会将int转换为unsigned int

 普通情况下会将范围小的隐式转换为范围大的,但对于int和unsigned int,就说不准哪个范围大了,经测试是会将int转换为unsigned int(被坑过。。。)

转载于:https://www.cnblogs.com/cdyboke/p/7780312.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值