Is this the correct syntax (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 must be used to print it, since the actual size may vary for each architecture."

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

'tsa, tsa'

+7
c sizeof printf
source share
5 answers

Yes, this syntax is correct (at least for C99). It looks like your compiler is not configured to handle it. Just pull out z and you will probably be fine. To be true, make sure your printf format specifiers match the size of the types. Including all the warnings your compiler will give you will probably help in this regard.

Your quote:

The z prefix must be used to print it, since the actual size may vary for each architecture.

refers to the fact that size_t (which is the type returned by the sizeof operator) can vary from architecture to architecture. z designed to make your code more portable. However, if your compiler does not support it, this will not work. Just play with the combinations %u , %lu , etc., until you get the point that makes sense.

+7
source share

A length modifier z was added to C in the C99 standard; you may have a compiler that does not support C99 .

If your C compiler does not support this, you can probably handle the sizes as an unsigned long:

 printf("%lu,%lu", (unsigned long)sizeof c, (unsigned long)sizeof(int)); 
+6
source share

Yes, but it only works with C99- complex compilers. From wikipedia :

z: for integer types, calls printf to wait for an integer argument of size size_t.

+2
source share

Did you tell your compiler you want him to think with the C99 brain? There is probably an opportunity to do this. For example, -std=c99 for gcc.

If your compiler does not support it, but you know others, you can use the PRId64 style style (disclaimer - PSEUDO CODE AHEAD ..):

 #ifdef __SOME_KNOWN_C99_COMPILER #define PORTUNSIGNED "zu" #else #define PORTUNSIGNED "u" #endif printf("%-11" PORTUNSIGNED " ways to skin a cat\n"); 

Most likely, it is better to get a compiler with functional support for c99.

+1
source share

I conducted a test using gcc 4.0. It works with -std=c99

0
source share

All Articles