Structure and Union
-A structure is a user-defined data type available in C that allows to combining data items of different kinds while a union is a special data type available in C that allows storing different data types in the same memory location.
-Similarities:
- Both are user-defined data types used to store data of different types as a single unit.
- Their members can be objects of any type, including other structures and unions or arrays. A member can also consist of a bit field.
- 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.
- 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.
- ‘.’ operator is used for accessing members.
- In structure each member get separate space in memory.
- The total memory required to store a structure variable is equal to the sum of size of all the members.
- In union, the total memory space allocated is equal to the member with largest size. All other members share the same memory space. This is the biggest difference between structure and union.
- All the members can be initialized while declaring the variable of structure. Only first member can be initialized while declaring the variable of union.
No comments:
Post a Comment