Search code examples
cgccprintflong-integerunsigned-integer

Why can't I print an unsigned int with printf in C?


For a school project, I'm trying to re-create the printf function of the stdio.h library in C.

I'm currently working on getting the unsigned int printing part working, but for some reason, why I try the real printf to print an unsigned int, it gives me a warning (which is considered as an error in my school). Could you someone explain me why?

Here is the code line I have used: printf("%u\n", 4294967295);. And here is the error I'm gettting:

main.c:18:17: warning: format specifies type 'unsigned int' but the argument has type 'long' [-Wformat]
        printf("%u\n", 4294967295);
                ~~     ^~~~~~~~~~
                %ld
1 warning generated.

Solution

  • All integer constants such as 4294967295 have a type, just like declared variables. The C compiler assigns a type to such a constant based on various intricate rules. A simplified explanation is that these rules basically boil down to:

    • "Does it fit in an int? If so, make it int."
    • "Otherwise does it fit in a long?" ... and so on.

    Note that these default types are signed types.

    On a 32 bit computer with 32 bit int, the largest number you can store in an int is 2^31 - 1 = 2147483647. 4294967295 is larger than that, so the compiler has to store it in a long. Hence the warning.

    Since 4294967295 would have fit in an unsigned int, so you could fix the code by simply forcing the compiler to treat the integer constant as unsigned: 4294967295u.