Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the point behind unions in C?

Tags:

c

unions

I'm going through O'Reilly's Practical C Programming book, and having read the K&R book on the C programming language, and I am really having trouble grasping the concept behind unions.

They take the size of the largest data type that makes them up...and the most recently assigned one overwrites the rest...but why not just use / free memory as needed?

The book mentions that it's used in communication, where you need to set flags of the same size; and on a googled website, that it can eliminate odd-sized memory chunks...but is it of any use in a modern, non-embedded memory space?

Is there something crafty you can do with it and CPU registers? Is it simply a hold over from an earlier era of programming? Or does it, like the infamous goto, still have some powerful use (possibly in tight memory spaces) that makes it worth keeping around?

like image 325
user978122 Avatar asked Mar 27 '13 23:03

user978122


1 Answers

Well, you almost answered your question: Memory. Back in the days memory was rather low, and even saving a few kbytes has been useful.

But even today there are scenarios where unions would be useful. For example, if you'd like to implement some kind of variant datatype. The best way to do this is using a union.

This doesn't sound like much, but let's just assume you want to use a variable either storing a 4 character string (like an ID) or a 4 byte number (which could be some hash or indeed just a number).

If you use a classic struct, this would be 8 bytes long (at least, if you're unlucky there are filling bytes as well). Using an union it's only 4 bytes. So you're saving 50% memory, which isn't a lot for one instance, but imagine having a million of these.

While you can achieve similar things by casting or subclassing a union is still the easiest way to do this.

like image 56
Mario Avatar answered Oct 27 '22 00:10

Mario