An union with a const and a nonconst member?

后端 未结 3 1243
伪装坚强ぢ
伪装坚强ぢ 2021-01-01 12:40

This appears to be undefined behavior

union A {
  int const x;
  float y;
};

A a = { 0 };
a.y = 1;

The spec says

Cr

3条回答
  •  梦谈多话
    2021-01-01 13:13

    It doesn't really make sense to have a const member of a union, and I'm surprised that the standard allows it. The purpose of all of the many limitations on what can go into a union is to arrive at a point where bitwise assignment will be a valid assignment operator for all members, and you can't use bitwise assignment to assign to a const int. My guess is that it's just a case that no one had previously thought of (although it affects C as well as C++, so it's been around for awhile).

提交回复
热议问题