c++c++11typesstdintcstdint

How to check if fixed width integers are defined


In C++, fixed width integers are defined as optional, but I can't seem 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?


Solution

  • To determine if a fixed-width integer type is provided, you can check if either of the corresponding [U]INT*_MAX or [U]INT*_MIN macros is defined.

    // may be necessary for your C++ implementation
    #define __STDC_LIMIT_MACROS 
    #include <cstdint>
    
    #ifdef INT32_MAX
    // int32_t must be available to get here
    int32_t some32bitIntVariable;
    #endif
    

    Per 7.20 Integer types <stdint.h>, paragraph 4 of the C11 standard (note the bolded parts):

    For each type described herein that the implementation provides, <stdint.h> shall declare that typedef name and define the associated macros. Conversely, for each type described herein that the implementation does not provide, <stdint.h> shall not declare that typedef name nor shall it define the associated macros.

    C++ inherits the C implementation via <cstdint>. See <cstdint> vs <stdint.h> for some details. Also see What do __STDC_LIMIT_MACROS and __STDC_CONSTANT_MACROS mean? for details on __STDC_LIMIT_MACROS.

    Thus, if int32_t is available, INT32_MAX and INT32_MIN must be #define'd. Conversely, if int32_t is not available, neither INT32_MAX nor INT32_MIN are allowed to be #define'd.

    Note though, as @NicolBolas stated in another answer, it may not be necessary to actually check.