gpt4 book ai didi

c - C语言中如何确定无符号长整型的范围?

转载 作者:行者123 更新时间:2023-12-02 05:29:44 26 4
gpt4 key购买 nike

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 character u or the character U)
    • long-suffix (the character l or the character L) or the long-long-suffix (the character sequence ll or the character sequence LL) (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 and MB_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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com