首页 > 解决方案 > 什么原因导致cfloat的INT32_MIN到size_t的类型转换溢出?

问题描述

在 Visual Studio 2019 中编译下面打印的代码会出现警告:C26450:... 使用更宽的类型来存储操作数。

#include <iostream>
#include <string>
#include <cfloat>

int main()
{
    size_t b = 4;
    std::cout << std::boolalpha << (b < INT32_MIN) << std::endl;

    return 0;
}

上面的代码返回:

true

用文字 4 替换 b 返回:

false

INT32_MIN 在 stdint.h 中定义为文字:(-2147483647i32 - 1)。

这个溢出错误在“<”操作中会发生什么?当 b 类型转换为 int 时,它会直观地起作用。

另请注意,添加以下内容表示没有溢出错误。

    std::cout << sizeof(size_t) << std::endl;
    std::cout << sizeof(int) << std::endl;

输出:

4
4

根据https://en.cppreference.com/w/cpp/types/size_t, size_t 是无符号的。

根据https://en.cppreference.com/w/cpp/language/operator_comparison, < 运算符导致转换为左侧的调用类型。这个文字(整数类型?)和 size_t 之间的转换会发生什么,使其等于 2147483648?

标签: c++stringimplicit-conversion

解决方案


size_t 是无符号格式。这是由于数据在内存中的表示方式。您将具有相同的行为,而 INT32_MIN 恰好是 0b10000000000000000000000000000000,即 2^31 / 2147483648(无符号)。如果您将其表示为带符号的 32 位数字,则它变为 -2^31 您应该结帐: https ://www.electronics-tutorials.ws/binary/signed-binary-numbers.html#:~:text=We%20have %20seen%20that%20negative,MSB )%20as%20a%20sign%20bit.&text=%20representation%20of%20a%20signed,then%20the%20number%20is%20negative。


推荐阅读