Union in C Programming Language

Union:- Union is like structures, contain members whose individual data types
may differ from one another. However, the members that compose aunion all share the same storage area within the computer’s memory, whereas each member within a structure is assigned its own unique
storage area. Thus, unions are used to conserve memory.

Union is a user-defined data type that refers to a memory location using several data types. Unions are conceptually similar to structures.
Similarly, C provides a data structure which fits our needs in this case called a union data type. 
Read Also:
  1. Data Structures
  2. Preprocessor Directives
  3. Linked List
A union type variable can store objects of different types at different times, however, at any given moment it stores an object of only one of the specified types.
Declaration:- The declaration of a union type must specify all the possible different types that may be stored in the variable. The form of such a declaration is similar to declaring a structure template. 
A union is declared using the union keyword. In union each members uses a single shared memory location which is equal to the size of its largest data member.
The general syntex of union declaration as follow:
The general syntex of union is:

For example, we can declare a union variable, person, with two members, a string and an integer. If the name is entered, we will use person to store the string, if an identification number is entered, we will use person to store an integer.
Here is the example of union declaration:

This declaration differs from a structure in that, when memory is allocated for the variable person, only enough memory is allocated to accommodate the largest of the specified types. The memory allocated for person will be large enough to store the larger of a integer or a 25 character array. Like structures, we can define a tag for the union, so the union template may be later referenced by name: 
Accessing Union Members:- Union members also access you in the same way as structure members are accessed.  First of all, you write the name of union.  After that, the name of the member is written by putting a dot Operator.



Enumeration:- Enumeration (or enum) is a user-defined data type in C. It is used to assign names to integral constants which make a program easy to read and maintain. The keyword enum is used to declare new enumeration types in C. Enum declaration is a follows:
enum flag{constant1, constant2, constant3,..); 
Variables of type enum can be defined in two ways:
  • enum week{Mon, Tue, Wed); 
     enum week day;
  • enum week(Mon, Tue, Wed)day; 
For example:

Post a comment

1 Comments