Difference & Similarities Between Structure and Union

« Previous
Next »

Difference Between Structure and Union

Union Structure
Memory Allocation A union shares the memory space among its members so no need to allocate memory to all the members. Shared memory space is allocated i.e. equivalent to the size of member having largest memory. Members of structure do not share memory. So A structure need separate memory space for all its members i.e. all the members have unique storage.
Keyword To define Union, ‘union’ keyword is used. To define Structure, ‘struct’ keyword is used.
Initialization Only the first member of Union can be initialized. All members of structure can be initialized.
Size Size of union is equivalent to the size of the member having largest size. Size of the structure is > to the sum of the each member’s size.
Member Access At a time, only one member of union can be accessed. Members of structure can be accessed individually at any time.

Similarities between Structure and Union

1. Both are user-defined data types used to store data of different types as a single unit.
2. Their members can be objects of any type, including other structures and unions or arrays. A member can also consist of a bit field.
3. Both structures and unions support only assignment = and sizeof operators. The two structures or unions in the assignment must have the same members and member types.
4. A structure or a union can be passed by value to functions and returned by value by functions. The argument must have the same type as the function parameter. A structure or union is passed by value just like a scalar variable as a corresponding parameter.
5. ‘.’ operator is used for accessing members.

« Previous
Next »