bergercookie bergercookie - 5 months ago 32
C Question

Print a size_t in a OS-independent architecture independent way

Suppose you have the following snippet of code:

include <stdio.h>
size_t nodeID = 5;
printf("nodeID = %lu", nodeID);

This will run without any warning being raised on a 64bit system but will generate a conversion warning for %lu on a 32bit system.

We can deal with it using the %z modifier

However this doesn't work on Visual Studio which uses the "I" modifier.

Is there any method available that solves this both in a architecture-independent and OS-independent way?


As you say, you can use the z modifier:

#include <stdio.h>
size_t nodeID = 5;
printf("nodeID = %zu\n", nodeID);

though as you say IIRC this may have compatibility issues with old MS compilers. You may be able to get around this with something like:

#ifdef _MSC_VER /* Untested MSC detection */
#define PRIuSIZE Iu
#define PRIuSIZE zu

#include <stdio.h>
size_t nodeID = 5;
printf("nodeID = %" PRIuSIZE "\n", nodeID);

Another way, which is architecture and OS independent in the sense that it doesn't rely on conditional preprocessor macros in your files, would be:

#include <stdio.h>
#include <inttypes.h>
size_t nodeID = 5;
printf("nodeID = %" PRIu64 "\n", (uint64_t) nodeID);

This would obviously rely on size_t being smaller or equal to 64 bits in length, which I believe it always is.