3 ms·
Tagged unions have always been around as runtime constructs, they just had different names (e.g. "variant"). In C it's understandable why they aren't part of th
by flohofwoe 6y ago
Tagged unions have always been around as runtime constructs, they just had different names (e.g. "variant"). In C it's understandable why they aren't part of the language: they would be the only data type that requires a "builtin" opaque struct type to hold the tag and payload union (e.g. something like this, but hidden from the programmer):
struct my_tagged_union {
enum my_tag_enum tag;
union {
....
} payload;
};
That would be a pretty big break with "tradition" for the C language ;) (e.g. it would be similar to a "builtin string type")
And of course tagged unions as "generic user-defined types" are much less convenient/useful than being directly integrated into the language syntax and type system.
- nicoburns 6y agoStructs aren't really any more fundamental than tagged unions though. They also contain bytes which are hidden from the language (padding). If a struct can have automatically generated padding bytes, why shouldn't a tagged union have an automatically generated tag?
- eqvinox 6y agoMostly because C structs have a very exactly bound memory representation, and padding bytes are just about the only thing you can - mostly - get away with not caring about. Coincidentally, even padding bytes break things technically. Since they're undefined, you - in theory - can't ever calculate a bytewise hash value over a struct that has any padding bytes. It's still done frequently, it's just nulled out beforehand and copying is bytewise anyway. Doesn't change the fact that to the spec letter it's undefined behaviour. GCC also added __builtin_clear_padding() recently. Hidden tags ... no. Just no.
- nicoburns 6y agoDoesn't need to be hidden. Just usable with language features (e.g. pattern matching) without accessing it explicitly.
- pornel 6y agoTagged unions built-in into the language can have layout optimizations, e.g. in Rust sizeof(Option<&i32>) == sizeof(&i32), because Rust knows it can repurpose NULL as the None value.