Search code examples
cprintfunsignedstdioconversion-specifier

Why doesn't the '+' sign work with printf for unsigned values?


I just wrote and ran following program. This just gave an unexpected output without + sign printed to U...MAX.

#include <limists.h>
#include <stdio.h>
#include <stdlib.h>
int main() {
    // ...
    printf("LLONG_MIN:  %+lli\n", LLONG_MIN);
    printf("LLONG_MAX:  %+lld\n", LLONG_MAX);
    printf("ULLONG_MAX: %+llu\n", ULLONG_MAX);
    return EXIT_SUCCESS;
}

And I got this:

CHAR_BIT:   8
SCHAR_MIN:  -128
SCHAR_MAX:  +127
UCHAR_MAX:  255
SHRT_MIN:   -32768
SHRT_MAX:   +32767
USHRT_MAX:  65535
INT_MIN:    -2147483648
INT_MAX:    +2147483647
UINT_MAX:   4294967295
LONG_MIN:   -2147483648
LONG_MAX:   +2147483647
ULONG_MAX:  4294967295
LLONG_MIN:  -9223372036854775808
LLONG_MAX:  +9223372036854775807
ULLONG_MAX: 18446744073709551615

Why is there no + sign printed for U..._MAX? How can I do that?


Solution

  • Why there is no + sign printed for U..._MAX? How can I do that?

    If it is unsigned you format it like this, moving the plus sign in front of the format specifier:

    printf("...: +%...\n", ...);
    

    If it is signed you format it like you currently do:

    printf("...: %+...\n", ...);
    

    I'd guess the reason printf doesn't sign it, is because it's unsigned. Many of the format specifiers are platform or library dependent, so you may encounter a library that adds the plus sign for an unsigned, when it sees %+.