user3149989
user3149989

Reputation: 37

Warning using format string with sprintf

    uint16_t foo;
    char     str[ 32 ];
    sprintf( str, "%6u", foo )

The previous code snippet throws a warning: #181 argument is incompatible with corresponding format string.

How would you get rid of that warning?

Peter

Upvotes: 1

Views: 6774

Answers (3)

Lucas Jones
Lucas Jones

Reputation: 20193

The %u format directive takes an argument of type unsigned int, which on your platform is probably bigger than 16 bits. On a 32-bit machine, a uint16_t will generally correspond to an unsigned short, which is printed with the %hu directive.

However, the reason for using the stdint.h types in the first place is portability. The (also standard) inttypes.h header file defines macros which contain the appropriate format directives for each stdint.h type for the current platform. In this case, the macro is called PRIu16, which can be used like so:

sprintf( str, "%6" PRIu16, foo );

Upvotes: 1

Jerry Coffin
Jerry Coffin

Reputation: 490178

"%u" is for unsigned, not uint16_t. You want something like:

#include <inttypes.h>

sprintf(str, "%6" PRIu16, foo);

Upvotes: 4

glglgl
glglgl

Reputation: 91049

Either cast your uint16_t to unsigned int, or replace "%6u" with "%6" PRIu16. That requires the header inttypes.h to be included.

Upvotes: 3

Related Questions