Home > Net >  Is accessing to std::array<std::uint8_t, 2> while std::uint16_t is active inside a union well
Is accessing to std::array<std::uint8_t, 2> while std::uint16_t is active inside a union well

Time:01-22

If I have an union

union Bytes {
  std::uint16_t bytes;
  std::array<std::uint8_t, 2> split_bytes;
};

and I use it like this

int main(){
  auto bytes = Bytes{0xFF'EE};
  // do something with bytes.split_bytes[0] and bytes.split_bytes[1]
}

Assuming the target machine is little endian, is my usage well-defined behavior?

CodePudding user response:

Is accessing to std::array<std::uint8_t, 2> while std::uint16_t is active inside a union well defined behavior?

Reading an inactive union member is undefined behaviour. Assigning an inactive trivial union member activates it.

Since the target of your attempted type punning is std::uint8_t which is unsigned char, you can use reinterpret_cast to read a std::uint16_t. However, as you seem to be aware, the order of the bytes varies between systems, and making assumptions about the order will result in a poorly portable program.

  •  Tags:  
  • Related