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

标签 c gcc integer range literals

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/

相关文章:

loops - 有没有办法遍历整数范围?

计算每行的平均值并存储在最后一个元素中

c - 不同类型的结构 extern

linux - 当将信号量减为零的进程崩溃时,如何恢复信号量?

c++ - "already a friend"警告什么时候有用?

r - 为什么 as.integer 在 R 中返回 NA?

c - 实现汉恩窗

c - 如何更改 scanf ("%d",&variable) 以从 C 中的命令行接收 argv

.c源文件和.so动态库一起编译

PHP 在 1 个变量中存储多个整数变量?