Compiler warning about printf() long unsigned int and uint32_t

18,154

Solution 1

uint32_t on x86 Linux with GCC is just unsigned int. So use fprintf(stream, "%4u", ...) (unsigned int) or better yet, fprintf(stream, "%4" PRIu32, ...) (the inttypes.h printf-string specifier for uint32_t).

The latter will definitely eliminate the compiler warning / error, and, additionally, is cross-platform.

Solution 2

The easiest way to reliably suppress the warning is with a cast:

printf( "%lu", ( unsigned long )x );

Solution 3

"long int" and "int" are different types in C++. You might be looking for the "u" format, which stands for "unsigned int". Of course, this depends on what "uint32_t" is a typedef for on your compiler.

Share:
18,154
pr1268
Author by

pr1268

Updated on June 16, 2022

Comments

  • pr1268
    pr1268 almost 2 years

    In my C code, I'm fprintfing a "%lu" and giving a uint32_t for the corresponding field. But, when I compile with -Wall in GCC (ver. 4.2.4), I get the following warning:

    writeresults.c:16: warning: format '%4lu' expects type 'long unsigned int', but argument 2 has type 
    `uint32_t'
    

    Aren't a uint32_t and long unsigned int the same thing on 32-bit architectures? Can this warning be avoided without eliminating the -Wall compiler switch or using a typecast (and if so, how)?

    Yes, I'm still using a 32-bit computer/arch/OS/compiler (too poor at the moment to afford new 64-bit HW). Thanks!

  • caf
    caf over 13 years
    ...and this is perfectly portable, since the minimal allowed size of unsigned long is exactly sufficient to hold all values of type uint32_t.
  • Conrad Meyer
    Conrad Meyer about 13 years
    Uh, where is the "bad" casting you're referring to? PRIu32 is the define that handles uint32_t correctly.
  • Ami
    Ami about 13 years
    Oh my, you are right! I'm wrong. Thanks. I'll delete my comment.
  • greggo
    greggo over 6 years
    In cases where they are the same size, the compiler is aware of this, and it can thus know ("%d", (long)x ) will work fine, but it's warning you because that construct won't work on other machines. Unless, of course, the 'long' is really an int32_t typedef, in which case it will work on any machine with int =32 bits. I'd prefer if there a way to back this off, and only warn about things that really are wrong in the current situation.