Memory position of elements in C/C++ union

后端 未结 2 1607
被撕碎了的回忆
被撕碎了的回忆 2020-12-09 17:48

I have a union in C like this:

union AUnion {
  struct CharBuf {
    char *buf;
    size_t len;
  } charbuf;
  uint8_t num;
  double fp_num;
};
相关标签:
2条回答
  • 2020-12-09 18:16

    In 6.7.2.1p16 the C standard guarantees that:

    The size of a union is sufficient to contain the largest of its members. The value of at most one of the members can be stored in a union object at any time. A pointer to a union object, suitably converted, points to each of its members (or if a member is a bit- field, then to the unit in which it resides), and vice versa.

    So, yes, you can rely on all members starting at the unions address (note this is the same for the first member of a struct).

    The C++ standard includes a similar sentence with respect to C-style (i.e. only C-style members) unions/structs, because C++ allows to pass unions to C functions which does require this layout.The relevant section in the C++ standard is 9.5.


    However, note there might be padding bits inside standard simple types (integers, floats). And their internal may vary (endianess). You also might violate strict aliasing rule (C: effective type).

    0 讨论(0)
  • 2020-12-09 18:40

    From my experience, I would say 'yes', though I've checked the C++14 standard and it even guarantees this. (c++11 will most likely have the same effects) Chapter 9.5 states: All non-static data members of a union object have the same address

    So, you can depend on this behavior.

    0 讨论(0)
提交回复
热议问题