The Union is same like Structure in which all members are stored at the same address. Members of a union can only be accessed one at a time. The union data type was invented to prevent memory fragmentation. The union data type prevents fragmentation by creating a standard size for certain data.
Just like with structures, the members of unions can be accessed with the. and -> operators. When the computer allocates memory for a program, it usually does so in one large block of bytes. Every variable allocated when the program runs occupies a segment of that block. When a variable is getting freed, it leaves a “hole” in the block allocated for the program. If this hole is of an unusual size, the computer may have difficulty allocating another variable to “fill” that hole, thus leading to inefficient memory usage.
Since unions have a standard data size, however, any “hole” left in memory by freeing a union can be filled by another instance of the same type of union. A union works because the space allocated for it is the space taken by its largest member; thus, the small-scale memory inefficiency of allocating space for the worst case leads to memory efficiency on a larger scale.
A union is declared in the same way as a structure. It has a list of members, as in the example below:
Declaring union variables is similar to declaring structure variables, if you have not read structure before, please visit our simplified explanation for structure here
union customer customer1;
The difference between union and structure:
|We can access all the members of a structure at any time.||Only one member of a union can be accessed at any time.|
|Memory is allocated for all variables.||Allocates memory for a variable which variable require more memory.|
|All members of the structure can be initialized||Only the first member of a union can be initialized.|
The C programming language provides a keyword called typedef, which you can use to define your own data type. Following is an example to define a term myDatatype for int
typedef int myDatatype
After this definition myDatatype can be used for int.
myDatatype a = 10;