Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Cool, so unions in C and C++ are a kind of sum type because the variable can have one of a set of types. More usually people think of tagged unions when they think of sum types, I believe Pascal's Variant Records are an example of tagged unions.


Thanks. Yes, I was thinking on the same lines. Don't remember whether Pascal also has this right now (more time since I used it than C), but in C, being the somewhat more flexible language that it is, IIRC you can also store a value of one type (out of the types of the sum type) in the union, and then read it back out as one of the other types. E.g. define a union with an int (say 16-bit) and a two-char (or two-byte) array, and then write into it as an int, and read it back out as two chars or two bytes. There are uses for such things, though I can't think of a good example of the top of my head. Okay, one use might be hardware interfacing, another might be conversion between big-endian and little-endian data values if you need to roll your own for some reason, I know there are libs for that).




Consider applying for YC's Winter 2026 batch! Applications are open till Nov 10

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: