Printing unsigned long long int Value Type Returns Strange Results

前端 未结 4 677
野的像风
野的像风 2021-01-17 13:45

I have a problem while using the printf function to print values of type unsigned long long int

I have no idea what\'s wrong. I\'m using De

相关标签:
4条回答
  • 2021-01-17 13:51

    ULONG_MAX refers to unsigned long and not to unsigned long long. For the latter, use ULLONG_MAX (note the extra L).

    You need to change the printf() calls like so:

    printf("unsigned long long int: \n%llu to %llu \n\n", 0ULL, ULLONG_MAX);
    printf("unsigned long long int: \n%llu to %llu \n\n", ULLONG_MAX, ULLONG_MAX);
    

    This ensures that the arguments to printf() match the format specifiers.

    0 讨论(0)
  • 2021-01-17 14:09

    This is wrong:

    printf("unsigned long long int: \n%llu to %llu \n\n", 0, ULONG_MAX);
    

    You use a unsigned long long format specifier, but you pass an int and an unsigned long value. Promotion rules mean you can be sloppy for everything int-sized or smaller, which does not apply to long long.

    Use casts:

    printf("unsigned long long int: \n%llu to %llu \n\n",
           0ULL, (unsigned long long) ULONG_MAX);
    

    Explanation: When passing arguments to printf, any type that can fit in an int is promoted to int, and then any type that can fit in an unsigned int is promoted to unsigned int. It is also okay to pass an unsigned type to a signed format specifier or vice versa as long as the value passed can be represented using the type specified by the format specifier.

    So you must be careful with long and long long, but you can be sloppy with int, short, and char.

    Most compilers have settings to make them warn you about this type of error, since it can be detected at compile-time fairly easily; GCC and Clang have -Wformat which results in the following warnings:

    test.c:5: warning: format ‘%llu’ expects type ‘long long unsigned int’, but argument 2 has type ‘int’
    test.c:5: warning: format ‘%llu’ expects type ‘long long unsigned int’, but argument 3 has type ‘long unsigned int’
    
    0 讨论(0)
  • 2021-01-17 14:10

    You are not passing unsigned long longs. You are passing an int (0) and unsigned long (ULONG_MAX). You must pass to printf() exactly what you promise to pass in the format string.

    Try this instead:

    printf("unsigned long long int: \n%llu to %llu \n\n", 0ULL, (unsigned long long)ULONG_MAX);
    
    0 讨论(0)
  • 2021-01-17 14:14

    long long int is a type from the C99 standard, MSVC doesn't support this. Take a compiler with C99 support (like MinGW for Windows) and it will work.

    0 讨论(0)
提交回复
热议问题