18

我想要做的是定义一个等于 2^30 的常数(我可能会将其更改为 2^34 之类的东西,所以我更喜欢有一个大于 32 位的房间)。

为什么以下最小(?)示例无法编译?

#include <stdint.h>
// test.cpp:4:33: error: expected primary-expression before numeric constant
// test.cpp:4:33: error: expected ')' before numeric constant
const uint64_t test = (uint64_t 1) << 30;
//const uint64_t test1 = (uint64_t(1)) << 30;// this one magically compiles! why?

int main() { return 0; }
4

3 回答 3

40

您可以使用宏:

UINT64_C

要定义一个 64 位无符号整数文字,标题提供了用于定义特定大小的整数文字的宏,我们在Header synopsiscstdint部分中看到:18.4.1

标头还定义了许多形式的宏:

包括:

加上形式的函数宏:

[U]INT{8 16 32 64 MAX}_C

我们必须回到 C99 草案标准来了解它们是如何工作的,7.18.4.1 最小宽度整数常量的宏部分说:

[...]如果 uint_least64_t 是 unsigned long long int 类型的名称,则UINT64_C(0x123) 可能会扩展为整数常量 0x123ULL

作为定义 64 位整数常量表达式的正确方法。不幸的是,这不是 cpprefernce 上的文档,但cplusplus.com确实记录了标头的此功能cstdint以及stdint.h 的 posix 参考

于 2014-03-12T20:37:44.973 回答
16

您正在寻找的语法是:

const uint64_t test = 1ULL << 30;

后缀ULL用于至少 64 位宽的无符号整数文字。

于 2014-03-12T20:35:56.250 回答
6

(uint64_t 1)不是有效的语法。投射时,您可以使用uint64_t(1)(uint64_t) 1。注释掉的示例有效,因为它遵循正确的转换语法,如下所示:

const uint64_t test = ((uint64_t)1) << 30;

编辑:虽然这直接回答了这个问题,但请参阅Shafik Yaghmour关于如何正确定义具有特定大小的整数常量的答案。

于 2014-03-12T20:34:34.713 回答