0

I'm working with a snippet of C code that looks like

char buf[16];
size_t i = 6;

sprintf(buf, "%d", i);

...and the compiler warns me that the 3rd argument is of type 'size_t' when the function is expecting an 'int'.

So I try telling it that it's going to get an unsigned int

sprintf(buf, "%u", i);

and now the compiler warns me that the 3rd argument is of type 'size_t' when the function is expecting an 'unsigned int'.


From what I read on other questions/answers regarding this issue, I cannot assume that size_t is an unsigned int, which explains the warning.

  • So how can I re-write the line so the compiler is happy (i.e. so the compiler is silent)?

Edit:

Before someone suggests it, I'm looking for a solution that actually addresses the slight possibility that something could go wrong. So forcing a typecast by going

sprintf(buf, "%d", (int)i);

or

sprintf(buf, "%u", (unsigned int)i);

is undesirable.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
roo
  • 103
  • 2

1 Answers1

0

C99 and C11 require a z modifier:

sprintf(buf, "%zu", i);

If MS Visual Studio has to be accommodated too, life is probably harder (because it doesn't adhere to either the C99 or C11 standard). According to MSDN, you need to use I instead of z.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278