Main Content

What are Unions (C programming)

Archive - Originally posted on "The Horse's Mouth" - 2008-06-08 15:09:57 - Graham Ellis

Structures are used to hold a whole lot of different pieces of data in a collection - by element name not number. Sometimes, you’ll only want to hold some elements of your structure in specific circumstances - a good example is where you have a whole lot of similar things you’re describing, but only a limited range of elements applied to each.

A very good example in real ’system’ programming is an X Windows event - each has a time stamp and a sequence number, and an event type, and each has a target window. But only some of them have X and Y co-ordinates, only some of them have keypresses and statuses, and so on. One possible way of holding such events would be a sparsely populated structure, but in practise this would be very wasteful of memory - so a union is used.