How can I confirm the range of unsigned long integer in C?

  • A+
Category:Languages

unsigned long has 8 bytes on my Linux gcc.

unsigned long long has 8 bytes on my Linux gcc, too.

So I think the range of integers they can show is from 0 min to (2^64 - 1)max.

Now I want to confirm if I'm correct.

Here is my code:

#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; } 

However, the code cannot be compiled and I get the following warning:

warning: integer constant is so large that it is unsigned 

Where did I do wrong? How can I modify the code ?


When you initialize num, you can append the "UL" for unsigned long and ULL for unsigned long long.

For example:

unsigned long a = 18446744073709551615UL; unsigned long long b = 18446744073709551615ULL; 

Also, use %zu instead of %d because sizeof return size_t.

According to 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 Sizes of integer types <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.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: