fik*_*tor 7 c++ compiler-errors const g++ int64
我要做的是定义一个等于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; }
Sha*_*our 28
你可以使用宏:
UINT64_C
为了定义一个64位无符号整数文字,该cstdint标题提供了用于定义特定大小的整数文字的宏,我们在章节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引用.
Zac*_*and 13
您正在寻找的语法是:
const uint64_t test = 1ULL << 30;
后修复ULL用于至少64位宽的无符号整数文字.
(uint64_t 1)是无效的语法.在施法时,你可以使用uint64_t(1)或(uint64_t) 1.注释掉的示例有效,因为它遵循正确的转换语法,如下所示:
const uint64_t test = ((uint64_t)1) << 30;
编辑:虽然这直接回答了问题,但请参阅Shafik Yaghmour关于如何正确定义具有特定大小的整数常量的答案.
| 归档时间: | 
 | 
| 查看次数: | 16825 次 | 
| 最近记录: |