C++隐式类型转换问题

问题描述:隐式类型转换问题

cpp 复制代码
if (optimize_param.dynamic_lds_size > 64UL * 1024UL)

这里在64后面加上UL表示"usigned long"类型的常量,为了防止在计算或者比较过程中出现类型转换的问题。

举例说明隐式类型转换问题

cpp 复制代码
#include <iostream>

int main(int argc, char const *argv[])
{
    unsigned int a = 10000U;
    int b = -1;
    /*
    详细说明:-1在计算机中以二进制补码的方式存储,即 1111 1111 1111 1111 1111 1111 1111 1111。
    int b = -1;        将 1111 1111 1111 1111 1111 1111 1111 1111 按照int类型解释,即-1
    转成unsigned int即,将 1111 1111 1111 1111 1111 1111 1111 1111 按照unsigned int类型解释,即4,294,967,295
    */
    if (a > b) // 这里进行比较的时候,b隐式的转成了a的类型unsigned int类型。即:b 变成 2^32大小
    {
        std::cout << "a > b" << std::endl;
    }
    else
    {
        std::cout << "a < b" << std::endl;
    }
    
    return 0;
}

修改方案:使用显式类型转换

隐式类型转换可能导致二进制解释的不一致,显示类型转换是让数据表示类型一致。

隐式类型转换中特别是 有符号和无符号之间得转换 会有二进制解释得问题。

cpp 复制代码
#include <iostream>

int main(int argc, char const *argv[])
{
    unsigned int a = 10000U;
    // int b = -1;
    int b = static_cast<unsigned int>(-1); //使用显式类型转换避免隐式类型转换存在的问题

    if (a > b)
    {
        std::cout << "a > b" << std::endl;
    }
    else
    {
        std::cout << "a < b" << std::endl;
    }
    
    return 0;
}
相关推荐
端平入洛2 天前
delete又未完全delete
c++
端平入洛3 天前
auto有时不auto
c++
郑州光合科技余经理3 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1233 天前
matlab画图工具
开发语言·matlab
dustcell.3 天前
haproxy七层代理
java·开发语言·前端
norlan_jame3 天前
C-PHY与D-PHY差异
c语言·开发语言
哇哈哈20213 天前
信号量和信号
linux·c++
多恩Stone3 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
QQ4022054964 天前
Python+django+vue3预制菜半成品配菜平台
开发语言·python·django
遥遥江上月4 天前
Node.js + Stagehand + Python 部署
开发语言·python·node.js