Search code examples
cprintfsizeof

Is using %zu correct syntax in a printf format string as shown in some C code found on Wikipedia?


I just found this code on Wikipedia.
Link: http://en.wikipedia.org/wiki/Sizeof#Use

The code:

/* the following code illustrates the use of sizeof 
 * with variables and expressions (no parentheses needed),
 * and with type names (parentheses needed)
 */

char c;

printf("%zu,%zu", sizeof c, sizeof(int));

It states that: "The z prefix should be used to print it, because the actual size can differ on each architecture."

I tried it on my compiler, but it gives the following result:

zu,zu

Solution

  • Yes that syntax is correct (at least for C99). Looks like your compiler isn't set up to handle it though. Just take out the z and you'll probably be fine. To be correct, make sure your printf format specifiers match the size of the types. Turning on all the warnings your compiler will give you probably helps out in that respect.

    Your quotation:

    The z prefix should be used to print it, because the actual size can differ on each architecture

    is referring to the fact that size_t (which is the type returned by the sizeof operator) can vary from architecture to architecture. The z is intended to make your code more portable. However, if your compiler doesn't support it, that's not going to work out. Just fiddle with combinations of %u, %lu, etc. until you get the output making sense.