cfloat的INT32_MIN到size_t的类型转换溢出是什么原因?
What causes the overflow of the type conversion of cfloat's INT32_MIN to 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;
}
上面的代码returns:
true
将 b 替换为文字 4 returns:
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=%20表示%20of%20a%20signed,则%20the%20number%20is%20negative.
在 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;
}
上面的代码returns:
true
将 b 替换为文字 4 returns:
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=%20表示%20of%20a%20signed,则%20the%20number%20is%20negative.