uintmax_t 不处理 128 位

Moh*_*HME 4 c++ compiler-errors primitive-types

我想在我的代码中定义千兆字节,所以我首先使用unsigned long. 然而unsigned long无法处理2 * gigabyte

\n\n

所以,我将其替换为long long但得到了相同的编译错误/警告:\n错误:表达式中的整数溢出[-Werror =溢出]

\n\n

最后,我查找了大整数,发现 uintmax_t 正是我所需要的,因为它是 128 位。

\n\n

不幸的是,我仍然遇到同样的错误。我猜有一个小错误,但我能找到它。

\n\n

请在下面找到相关代码:

\n\n
#define kilobyte 1024\n#define megabyte 1024 * kilobyte\n#define gigabyte 1024 * megabyte\nuintmax_t threshold = 2 * gigabyte;\n
Run Code Online (Sandbox Code Playgroud)\n\n

最后,运行“make”后

\n\n
g++ -Wall -Wextra -Werror -pedantic -pthread -std=c++0x -g  -o lcr main.cpp\n
Run Code Online (Sandbox Code Playgroud)\n\n

我有:

\n\n
main.cpp: In function \xe2\x80\x98int main(int, char**)\xe2\x80\x99:\nmain.cpp:104:17: error: integer overflow in expression [-Werror=overflow]\ncc1plus: all warnings being treated as errors\n
Run Code Online (Sandbox Code Playgroud)\n

Col*_*mbo 5

两个 s 的乘积int显然仍然是 类型int- 并且我们在宏中处理的文字是 类型int
1024 3 = 2 30大约可以用 32 位表示int。然而,2*2 30 = 2 31对于 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;
Run Code Online (Sandbox Code Playgroud)

由于对 的操作数执行通常的算术转换*,因此不会发生溢出。