Why it is different between -2147483648 and (int)-2147483648(为什么 -2147483648 和 (int)-2147483648 不同)
问题描述
当我在Windows7 x64下运行以下代码,使用MinGW的GCC编译时,结果似乎下溢:
When I run the following code under Windows7 x64, compiled with GCC of MinGW, the result seems to be underflowed:
cout<<-2147483648 ; //Output: 2147483648
但是当我将它分配给一个整数变量时,或者只是将它转换为 int 类型:
but when I assigned it to a integer variable, or just simply convert it to the int type :
cout<<(int)-2147483648 ; //Output: -2147483648
那么,我之前的代码版本有什么问题?不是int类型吗?或者整数的下限到底是多少?非常感谢.
So, what's wrong with the previous version of my code? Istn't it the type int? or what the lower bound the Integer is exactly? Many thanks.
推荐答案
2147483648 在您的系统上不适合 int 或 long,因此它被视为 unsigned long 类型的常量.(正如 ouah 在评论中指出的那样,它在标准 C++ 中是未定义的行为,但您的编译器将其作为扩展接受.)对无符号整数值取反是可能的,但会产生另一个无符号整数值,而不是负数.否定 2147483648UL 会产生 2147483648UL(假设与您的系统一样,unsigned long 是 32 位类型).
2147483648 doesn't fit into an int or a long on your system, so it's treated as a constant of type unsigned long. ( as ouah pointed out in the comments, it's undefined behaviour in standard C++, but your compiler accepts it as an extension.) Negating an unsigned integer value is possible, but results in another unsigned integer value, never a negative number. Negating 2147483648UL produces 2147483648UL (assuming, as is the case on your system, that unsigned long is a 32 bit type).
将其转换为 int
会产生实现定义的结果,通常是您看到的结果,但不一定.你可以通过写-2147483647 - 1得到你想要的结果而不需要任何转换.
Casting that to int
produces an implementation-defined result, commonly the result you see, but not necessarily. You can get the result you want without any conversions by writing -2147483647 - 1.
这篇关于为什么 -2147483648 和 (int)-2147483648 不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么 -2147483648 和 (int)-2147483648 不同


基础教程推荐
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 从 std::cin 读取密码 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01