Cross-platform primitive data types in C++

前端 未结 7 2484
鱼传尺愫
鱼传尺愫 2021-02-14 07:04

Unlike Java or C#, primitive data types in C++ can vary in size depending on the platform. For example, int is not guaranteed to be a 32-bit integer. Various compi

7条回答
  •  面向向阳花
    2021-02-14 07:22

    There is a stdint.h header defined by the C99 standard and (I think) some variant or another of ISO C++. This defines nice types like int16_t, uint64_t, etc... which are guaranteed to have a specific size and representation. Unfortunately, it's availability isn't exactly standard (Microsoft in particular was a foot dragger here).

    The simple answer is this, which works on every 32 or 64 bit byte-addressable architecture I am aware of:

    • All char variables are 1 byte
    • All short variables are 2 bytes
    • All int variables are 4 byte
    • DO NOT use a "long", which is of indeterminate size.
    • All known compilers with support for 64 bit math allow "long long" as a native 64 bit type.

    Be aware that some 32 bit compilers don't have a 64 bit type at all, so using long long will limit you to 64 bit systems and a smaller set of compilers (which includes gcc and MSVC, so most people won't care about this problem).

提交回复
热议问题