Hacker News new | ask | show | jobs
by commentereleven 3827 days ago
Would that mean not being able to use const in unions?
1 comments

I've never actually seen a union used in a C++ codebase. What's the usecase? I know people use them in C for bitfields, but outside of embedded (which is almost always just pure C) that just doesn't seem to come up
Embedded can be almost anything, C/C++/java and so on. I've seen microcontrollers with 8K of program space, written in C++. Why? Because it optimizes better than the 'C' programmer does.

Unions are used for interpreting any kind of record stream. Reading serialized binary objects from a file? Use a union. Network packets? A union.

When reading from a binary source, I've seen that, instead of unions, the char pointer will be cast to a pointer to the appropriate data structure. What is the advantage of using a union instead of casting?
Well, for one, unions have defined behavior in C, while passing pointers around and casting them randomly doesn't.

I don't know if this is the best example. Generally you see unions in C to cover "tagged unions", I.e. Those things that would be subsumed by algebraic data types in other languages.

Ah, got it. I am used to C++, where accessing the non-active member of the union is undefined behavior. Thank you.
The usual way to do this via memcpy, rather than either a union (requires some non-portable extension like "packed") or pointer casting (invokes undefined behavior if alignment isn't satisfied).
Here's one use of union in a C++ code base (sf::Event): http://www.sfml-dev.org/documentation/2.3.2/classsf_1_1Event...
Tagged pointers - hiding a few bytes in a pointer address.
Tagged unions are often used as substitute for the missing std::variant
Tagged unions are often used in C to provide a form of Sum Type.