Structure
A structure is a user-defined data type that allow to store different datatypes of elements in the separate memory location. The “struct” keyword is used to define structure.
Syntax :-
struct structure_name { data_type variable_name1; data_type variable_name2; . . data_type variable_nameN; }; |
Declaration of structure variable :
struct book { char name[20] ; float price ; int pages ; }; |
Initialization of structure variable :
struct book { char name[20] ; float price ; int pages ; }; struct book b1 = { “C”, 270.00, 400 }; struct book b1 = { “java”, 400.00, 500 }; |
Union
A union is also user-defined data type that allow to store different datatypes of elements in the same memory location. The “union” keyword is used to define union.
Syntax :-
union union_name { data_type variable_name1; data_type variable_name2; . . data_type variable_nameN; }; |
Declaration of Union Variable :
union book { char name[20] ; float price ; int pages ; }; |
Initialization of Union Variable :
union book { char name[20] ; float price ; int pages ; }; union book b1 = { “C”, 270.00, 400 }; union book b1 = { “java”, 400.00, 500 }; |
Differences between structure and union
Structure |
Union |
The “struct” keyword is used to define structure. |
The “union” keyword is used to define union. |
Structure is allocates storage space for all its members separately. |
Union allocates one common space for all its members. |
Structure occupies higher memory space. |
Union occupies less memory space other than structure. |
We can access all members of structure at a time. |
We can access only one members of union at a time. |
All members may be initialized. |
Only first member may be initialized. |