fixed length data types in C/C++

后端 未结 11 1010
春和景丽
春和景丽 2020-12-23 14:34

I\'ve heard that size of data types such as int may vary across platforms.

My first question is: can someone bring some example, what goes wrong, when p

11条回答
  •  春和景丽
    2020-12-23 15:04

    For the first question: Integer Overflow.

    For the second question: for example, to typedef an unsigned 32 bits integer, on a platform where int is 4 bytes, use:

     typedef unsigned int u32;
    

    On a platform where int is 2 bytes while long is 4 bytes:

    typedef unsigned long u32;
    

    In this way, you only need to modify one header file to make the types cross-platform.

    If there are some platform-specific macros, this can be achieved without modifying manually:

    #if defined(PLAT1)
    typedef unsigned int u32;
    #elif defined(PLAT2)
    typedef unsigned long u32;
    #endif
    

    If C99 stdint.h is supported, it's preferred.

提交回复
热议问题