Difference between Structure and Union in C Language
Structure
A structure is a user-defined compound data type that consists of data members related to a person or an item. It has the following syntax:
struct tag_name { type data_member1; type data_member2; ………….. ……….. };
where type is the data type of data_members,
data_member1, data_member2 are available which are related to a person or item.
tag_name is the name of the structure which refers to the new compound data type.
Example :
struct employee { int id_no; char ename[25]; int salary; };
Union
A union also consists of data members but only one data member is active at a time. The union is useful in cases where the user selects any one data member for the application. It has the following syntax:
union tag_name { type data_member1; type data_member2; .............. ........... };
where type is the data type of data_members,
data_member1, data_member2 are the variable.
tag_name is the name of the union.
Structure vs Union
1. The keyword struct is used to declare a structure. | 1. The keyword union is used to declare a union |
2. All data members in a structure are active at time. | 2. Only one data member is active at a time. |
3. It is useful to declare a compound data type to group data members related to a person or item. | 3. It is useful in certain cases where the user will select any one data member in the group of the data members. |
4. It is commonly used in most of the applications. | It is not commonly used. |