Hacker News new | ask | show | jobs
by thamer 1788 days ago
You've mentioned this several times on this page, but this is still incorrect.

The C standard references "struct or union" all over the place because the two are so similar. The distinction is of course made clear in multiple places, but one that seems relevant here is:

> As discussed in 6.2.5, a structure is a type consisting of a sequence of members, whose storage is allocated in an ordered sequence, and a union is a type consisting of a sequence of members whose storage overlap. (ISO/IEC 9899:201x, §6.7.2.1, #6)

That's it. There's nothing about undefined behavior if you access one member and then another later. In fact there's even a paragraph which mentions doing just 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 bitfield, then to the unit in which it resides), and vice versa. (ISO/IEC 9899:201x, §6.7.2.1, #16)

A pointer to the union points to each of its members, and can be dereferenced to access it.

std::variant is not used in C; C and C++ are two different languages.

1 comments

> The size of a union is sufficient to contain the largest of its members.

Correct me if I'm wrong, but there is no part of the C spec that says this:

When initializing a union member that is smaller than the largest member, the remaining bytes will always automatically be initialized to zero.

If I'm right then the following caveat must be added to your statement:

> A pointer to the union points to each of its members, and can be dereferenced to access it.

... if and only if the member which was originally initialized is at least as large as the other member being accessed.

In other words, if you write your program in a way that ensures it will only compile when all union members are exactly the same size, and you have mandatory tooling to make sure that any changes to said union follow the same rule by force of compilation errors, then and only then can you claim what you claimed without the threat of undefined behavior.