unsigned long 在我的 Linux gcc 上有 8 个字节。
unsigned long long 在我的 Linux gcc 上也有 8 个字节。
所以我认为他们可以显示的整数范围是从0 min到(2^64 - 1)max。
现在我想确认我是否正确。
这是我的代码:
#include <stdio.h>
int main(void)
{
printf("long takes up %d bytes:\n", sizeof(long));
printf("long long takes up %d bytes:\n", sizeof(long long));
unsigned long a = 18446744073709551615;
a++;
printf("a + 1 = %lu\n", a);
unsigned long long b = 18446744073709551615;
b++;
printf("b + 1 = %llu\n", b);
return 0;
}
但是,代码无法编译,我收到以下警告:
warning: integer constant is so large that it is unsigned
我哪里做错了?如何修改代码?
最佳答案
初始化num时,可以为unsigned long
附加"UL"和 ULL 表示 unsigned long long
.
例如:
unsigned long a = 18446744073709551615UL;
unsigned long long b = 18446744073709551615ULL;
另外,使用 %zu
而不是 %d
因为 sizeof 返回 size_t
.
根据 cppreference :
- integer-suffix, if provided, may contain one or both of the following (if both are provided, they may appear in any order:
unsigned-suffix
(the characteru
or the characterU
)long-suffix
(the characterl
or the characterL
) or thelong-long-suffix
(the character sequencell
or the character sequenceLL
) (since C99)
C standard 5.2.4.2.1整数类型的大小 <limits.h>
:
1 The values given below shall be replaced by constant expressions suitable for use in #if preprocessing directives. Moreover, except for
CHAR_BIT
andMB_LEN_MAX
, the following shall be replaced by expressions that have the same type as would an expression that is an object of the corresponding type converted according to the integer promotions. Their implementation-defined values shall be equal or greater in magnitude (absolute value) to those shown, with the same sign.
关于c - C语言中如何确定无符号长整型的范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50036741/