c++ - 什么原因导致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?
解决方案
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。
推荐阅读
- javascript - 使用 css 在反应选择中设置我的占位符
- mongodb - 使用 Spring Boot MongoDb 无法使用 DBRef 创建“空”MongoDb 文档
- python - Tensorflow 2.0 - 这些模型预测是否代表概率?
- matlab - 使用具有中心极限定理的 Matlab 的偏置模具的 PDF 和 CDF
- ios - 快速图像/按钮滑块
- javascript - 使用 Webpack 构建 Gatsby 组件无法转换 Gatsby 模块
- bash - 如何在 { grouped } shell 命令中设置父变量?
- javascript - 在 React 中,等待链在中间停止时如何调试?
- c# - 如何将类似于json对象的对象转换为c#?
- javascript - 如何在 Firefox 71.0 中使用 Javascript 中的 localStorage