我想在我的代码中定义 gigabyte,所以我首先使用了 unsigned long
。但是,unsigned long
无法处理 2 * gigabyte
。
所以,我用 long long
替换了它,但我得到了同样的编译错误/警告:
错误:表达式中的整数溢出 [-Werror=overflow]
最后,我查找了大整数,发现 uintmax_t 是我需要的,因为它是 128 位。
不幸的是,我仍然遇到同样的错误。我想有一个小错误,但我能找到它。
相关代码如下:
#define kilobyte 1024
#define megabyte 1024 * kilobyte
#define gigabyte 1024 * megabyte
uintmax_t threshold = 2 * gigabyte;
最后,在运行“make”之后
g++ -Wall -Wextra -Werror -pedantic -pthread -std=c++0x -g -o lcr main.cpp
我得到了:
main.cpp: In function ‘int main(int, char**)’:
main.cpp:104:17: error: integer overflow in expression [-Werror=overflow]
cc1plus: all warnings being treated as errors
最佳答案
两个产品int
s 显然仍然属于 int
类型- 我们在您的宏中处理的文字类型为 int
.
10243 = 230 几乎可以用 32 位 int
表示.然而,2*230 = 231 对于 32 位签名的 int
来说正好太大了。举行。
这可以通过将常量定义为适当类型的对象来解决:
const std::uintmax_t kilobyte = 1024;
const std::uintmax_t megabyte = 1024 * kilobyte;
const std::uintmax_t gigabyte = 1024 * megabyte;
const std::uintmax_t threshold = 2 * gigabyte;
感谢对 *
的操作数执行通常的算术转换, 不会发生溢出。
关于c++ - uintmax_t 不处理 128 位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28053801/