platform format without warnings
This question already has an answer here:
For size_t
, assuming you have a sufficiently modern C library, use %zu
.
If you can't use the z
modifier (some older libraries unfortunately don't support it), cast to a wide-enough known type when printing, and then use a width specifier appropriate to that type:
size_t sz = sizeof(whatever);
...
printf("%lu", (unsigned long)sz);
This works as long as you're never working with a size larger than 4 billion or so, ie that can fit in 32 bits. If you're on a system where size_t
is 64 bits but long
is 32, you've theoretically got the problem of a size which size_t
can hold but %lu
can't print. Whether this is a problem for you, and what to do if it is, is up to you. (The ideal solution, if your library supports it, is to go back to %zu
, which is the preferred solution and doesn't have this problem in 32-bit, 64-bit, or any other sized environments. Or I guess you could use unsigned long long
and %llu
.)
This particular warning can be avoided by using explicitly sized integers instead of the native data types.
#include <cstdint>
int8_t a = 15; //usually an alias for char
uint16_t b = 4980; //usually an alias for unsigned short
uint32_t c = 1234567890; //usually an alias for unsigned int or unsigned long
int64_t d = 908070605040302010ll; //usually an alias for long long
The trick with the sized integers is that if, for example, long
were 32-bits on one platform, but 64 bits on another, any uses of long
would be non-portable. But int64_t
will always be 64-bits, or else it simply won't exist on the given platform.
In your case specifically, your code seems to be presuming that size_t
will always be 64-bits, but there's no guarantee of that. So you should be using uint64_t
instead, which guarantees that whatever underlying data type it ends up using, it will be 64 bits (and unsigned, which is the only guarantee associated with size_t
).
上一篇: 什么是晶体管级别的“if”声明?
下一篇: 平台格式没有警告