C++ Logo

std-discussion

Advanced search

Re: Value of non-active data member byte in constexpr union?

From: Shafik Yaghmour <yaghmour.shafik_at_[hidden]>
Date: Thu, 16 Mar 2023 13:30:55 -0700
Hello,

When you assign to b[0] a is no longer the active member of the union
and therefore reading from it is undefined behavior, we can see this
from the diagnostic in this example program:
https://godbolt.org/z/1PjfzjEf8


On Thu, Mar 16, 2023 at 1:20 PM Stephan Bergmann via Std-Discussion
<std-discussion_at_[hidden]> wrote:
>
> I'm trying to understand what the semantics of the C++20 program
>
> > struct S {
> > union {
> > char a[2];
> > char b[1];
> > };
> > constexpr S() {
> > a[1] = 2;
> > b[0] = 3;
> > }
> > };
> > constexpr S s;
> > int main() {
> > return reinterpret_cast<unsigned char const *>(&s)[1];
> > }
>
> is, but I fail to find anything relevant in the standard. Plausible
> results could be UB, "return 0" (which is what at least Clang and GCC
> appear to agree on), or even "return 2". Any pointers?
>
> --
> Std-Discussion mailing list
> Std-Discussion_at_[hidden]
> https://lists.isocpp.org/mailman/listinfo.cgi/std-discussion

Received on 2023-03-16 20:31:09