top | item 47074552

(no title)

cataphract | 10 days ago

It was an example. The point was to make untagged unions usable in constant evaluation contexts.

What I was surprised with was that their union code was valid. I thought accessing a union member that was not active was valid in C, but not in C++.

discuss

order

matthewkayin|10 days ago

I would think it would have to work the same in both since otherwise C code using that behavior would not compile in C++, right?

I am not a C++ expert, but I'm surprised to hear that it is considered UB to access the other member since as far as I can tell a union is just a chunk of memory that can be interpreted differently depending on which union member you access?

So, if you had a union { bool b, char c }, and you set b = false, then I would think that accessing c would predictably give you a value of '\0'.

Granted, you probably shouldn't go around accessing an inactive union member like that, but when people say it's UB they make it sound like it's impossible to guarantee what data will be inside that byte, and it seems to me like that isn't true.