The union in C combines several variables of different type, like a structure. However, it keeps in memory only one of its members at any given time. This allows for memory optimization, where RAM is critical – usually embedded projects.
If you are not familiar with structures, you should read about them. We use them more often and once you understand them you will learn about unions in several seconds ;)
A union will allocate only the minimum amount of memory to hold its biggest member. This means that if we group together a char, int and a short variable, we will allocate only the memory for the int. You should try it – create such example and test it with the sizeof operator. In this case it should return 4 or 8, depends on the int size in your environment.
The variables will share that memory. Each time we write in one member, it will overwrite the data of the other variables. For that reason, we need a helper variable to keep track to the member that was last assigned. In order to be effective, the union should save more memory than its helper variable. More on this, in a minute.
The syntax is pretty much the same as that of a structure with the difference, of course, that here we use the keyword union. The rest is the same. We can create unions in our header files, or in our source files. I prefer to keep it clean and separate the code from the types, so I define them in separate headers.
Later, we can access the members with the dot '.' and the arrow '->' operators. We use the ‘.’ if we access them through a regular variable. We use the ‘->’ if we access them through a pointer.
pointerToAUnion->memberName = 5;
We can create a list of variables immediately after the definition of the union, like this:
The second way is to use the tag. Here is how to do it:
union A instance1, instance2...;
Now we can put some information inside and use it. We also add the helper variable to keep track:
The source of the examples is available for download from here.
In contrast to structures, unions don’t use memory padding for memory alignment. After all, the very idea of using a union in C is to reduce memory usage.
In practice, we use unions with more complex data, than the examples above. Normally we will put two or more structures in one union. This is, because a structure holds several/many variables. This means that we can save much more memory if we only need one of the structures at a time.