bergercookie
bergercookie

Reputation: 2760

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?

Upvotes: 3

Views: 285

Answers (1)

abligh
abligh

Reputation: 25119

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
#else
#define PRIuSIZE zu
#endif
#define QUOTE(name) #name
#define STR(macro) QUOTE(macro)
#define USIZE_STR STR(PRIuSIZE)

#include <stdio.h>
size_t nodeID = 5;
printf("nodeID = %" USIZE_STR "\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.

Upvotes: 5

Related Questions