I recently came across a great data structures book,"Data Structures Using C" (c) 1991, at a local Library book sale for only $2. As the book's title implies, the book covers data structures using the C programming language.
I got the book knowing it would be out-dated but would probably contain lots of advanced C topics that I wouldn't encounter elsewhere.
Sure enough within 5 minutes I found something I didn't know about C. I came across a section talking about the
union keyword and I realized that I had never used it, nor ever seen any code that does. I was grateful for learning something interesting and quickly bought the book.
For those of you not knowledgeable about what a union is, the book uses a good metaphor to explain:
To fully understand the concept of a union, it is necessary to examine its implementation. A Structure may be regarded as a road map to an area of memory. It defines how the memory is to be interpreted. A union provides several different road maps for the same area of memory, and it is the responsibility of the programmer to determine which road map is in current use. In practice, the compiler allocates sufficient storage to contain the largest member of the union. It is the road map, however, that determines how that storage is to be interpreted.
I could easily come up with contrived situations or hacks where I would use a Union. (But I am not interested in contrived situations or hacks...)
Have you used or seen an implementation where using Union solved the problem **more elegantly** than not using a Union?
Added bonus if you include a quick explanation of why using union was better/easier than not using a union.