fixed length data types in C/C++

后端 未结 11 1017
春和景丽
春和景丽 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 14:55

    I know people solve this issue with some typedefs, like you have variables like u8,u16,u32 - which are guaranteed to be 8bits, 16bits, 32bits, regardless of the platform

    There are some platforms, which have no types of certain size (like for example TI's 28xxx, where size of char is 16 bits). In such cases, it is not possible to have an 8-bit type (unless you really want it, but that may introduce performance hit).

    how is this achieved usually?

    Usually with typedefs. c99 (and c++11) have these typedefs in a header. So, just use them.

    can someone bring some example, what goes wrong, when program assumes an int is 4 bytes, but on a different platform it is say 2 bytes?

    The best example is a communication between systems with different type size. Sending array of ints from one to another platform, where sizeof(int) is different on two, one has to take extreme care.

    Also, saving array of ints in a binary file on 32-bit platform, and reinterpreting it on a 64-bit platform.

提交回复
热议问题