From a response to some question yesterday, I learned that it is nonportable and unsafe to write into one union member and read the value from another member of a different type, assuming underlying alignment of the members. So after some research I found a written source that repeats this claim and specifies a popular example – using union of int and float to find the binary representation of a float.
So, understanding that this assumption is not safe, I wonder – except for saving memory (duh…) what real use is there to unions?
Note: that is, under Standard C. Clearly, for a specific implementation, the rules are known in advance and can be taken advantage of.
EDIT: the word “unsafe”, due to association of recent years, is probably a bad choice of wording, but I think the intention in clear.
EDIT 2: Since this point repeats in the answers – saving memory is a valid argument. I wanted to know if there was something beyond that.
Yes.
The provide a way of creating generic containers. Though, to get polymorphic behavior you must implement a vtable or type switching yourself…
There are, however, one of those features that you only use when you need them and need rather rarely.