Where is a union used, i mean what is the use of a union?
Where is a union used, i mean what is the use of a union?
if you want a chunk of memory that can be used in more than one way, you can use a union to accomplish this.
for instance lets say you want a long (4 bytes) but you also want to be able to easily access each of the 4 bytes you could do a union of a long and a 4 char struct.
as always there are of course other ways to do this but union is a nice one in some cases.
"You are stupid! You are stupid! Oh, and don't forget, you are STUPID!" - Dexter
Unions are used for reducing storage costs, accessing data with different internal representations, and creating a poor man's polymorphism.Originally Posted by studentc
Reducing storage costs entails exactly what you would think. Instead of using separate memory blocks for objects that will not exist simultaneously, you place them in a union and only use one at a time to save space. Accessing data with different internal representations was already described previously by FillYourBrain, so I won't go into further detail unless you want me to. The poor man's polymorphism is fairly simple. You use a structure with two members: a type identifier and a union of the different types. The union shares storage among different objects and the type identifier tells which object is in use at the time. This also saves space, but the intention is a heterogeneous data type rather than space efficiency.