Search code examples
cgcc64-bitlong-integer

gcc long long int width same as int


I am testing gcc version 8.2

gcc seems to be treating long long int as int. Is there any way to fix this?

Here is the code:

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <float.h>

int main(int argc, char** argv) {

    printf("INT_MAX     :   %d\n", INT_MAX);
    printf("INT_MIN     :   %d\n", INT_MIN);
    printf("LONG_MAX    :   %ld\n", (long) LONG_MAX);
    printf("LONG_MIN    :   %ld\n", (long) LONG_MIN);
    printf("UINT_MAX    :   %u\n", (unsigned int) UINT_MAX);
    printf("ULLONG_MAX   :   %lu\n", (unsigned long long int) ULLONG_MAX);
    printf("Big Integer   :   %lu\n", (unsigned long long int) 1234567890123456);

    printf("%d\n", sizeof(long long int));
    return 0;
}

output:

INT_MAX     :   2147483647
INT_MIN     :   -2147483648
LONG_MAX    :   2147483647
LONG_MIN    :   -2147483648
UINT_MAX    :   4294967295
ULLONG_MAX   :   4294967295
Big Integer   :   1015724736
8

C:\prog_c\c_pro>gcc --version gcc (MinGW.org GCC-8.2.0-5) 8.2.0 Copyright (C) 2018 Free Software Foundation, Inc...


Solution

  • printf needs to know the difference between long and long long, and that's with the %lld (signed) or %llu (unsigned):

        printf("ULLONG_MAX  :   %llu\n", (unsigned long long int) ULLONG_MAX);
        printf("Big Integer :   %llu\n", (unsigned long long int) 1234567890123456);
    

    This should work as you expect. Otherwise, printf is grabbing only part of the bits from the stack, giving the bad answers you were getting.

    Furthermore, if you'd turn on compiler warnings it would have told you this:

    long.c: In function ‘main’:
    long.c:13:5: warning: format ‘%lu’ expects argument of type ‘long unsigned int’, but argument 2 has type ‘long long unsigned int’ [-Wformat=]
         printf("ULLONG_MAX  :   %lu\n", (unsigned long long int) ULLONG_MAX);
         ^
    long.c:14:5: warning: format ‘%lu’ expects argument of type ‘long unsigned int’, but argument 2 has type ‘long long unsigned int’ [-Wformat=]
         printf("Big Integer :   %lu\n", (unsigned long long int) 1234567890123456);
         ^
    long.c:16:5: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘long unsigned int’ [-Wformat=]
    

    It's a really, really good idea to always turn on the warnings - with GCC I normally use -W -Wall - so it tells me what I'm getting wrong.

    Compiler warnings are like SO but without the downvotes :-)