In C++, fixed width integers are defined as optional, but I can't seems to find the recommended way to check if they are actually defined.
What would be a portable way to check if fixed width integers are available?
In C++, fixed width integers are defined as optional, but I can't seems to find the recommended way to check if they are actually defined.
What would be a portable way to check if fixed width integers are available?
Nicol Bolas
On
Broadly speaking... you don't.
If you need to use the fixed-sized integer types, then that means that you explicitly need those types to be of their specific sizes. That is, your code will be non-functional if you cannot get integers of those sizes. So you should just use them; if someone uses your code on a compiler that lacks said types, then your code will not compile. Which is fine, because your code wouldn't have worked if it did compile.
If you don't actually need fixed-sized integers but simply want them for some other reason, then use the int_least_* types. If the implementation can give you exactly that size, then the least_* types will have that size.
To determine if a fixed-width integer type is provided, you can check if either of the corresponding
[U]INT*_MAXor[U]INT*_MINmacros is defined.Per 7.20 Integer types
<stdint.h>, paragraph 4 of the C11 standard (note the bolded parts):C++ inherits the C implementation via
<cstdint>. See<cstdint>vs<stdint.h>for some details. Also see What do__STDC_LIMIT_MACROSand__STDC_CONSTANT_MACROSmean? for details on__STDC_LIMIT_MACROS.Thus, if
int32_tis available,INT32_MAXandINT32_MINmust be#define'd. Conversely, ifint32_tis not available, neitherINT32_MAXnorINT32_MINare allowed to be#define'd.Note though, as @NicolBolas stated in another answer, it may not be necessary to actually check.