Structure and union both are user demarcated data types which contains variables of different data types. Both of them have same syntax for definition, declaration of variables and for retrieving members. Still there are many differences between structure and union. In structure every member get separate space in memory. In union, the total memory space allocated is equal to the member with biggest size. All other members share the same memory space. This is the biggest difference between structure and union.
What is Structure?
Structure uses all the memory of its member. In structure we can admission any member in any sequence.
What is Union?
Union uses the largest member’s memory space. In union we can access only that variable whose value is recently stored.
- In structure every member get separate space in memory. In union, the total memory space allocated is equal to the member with biggest size. All other members share the same memory space. This is the biggest difference between structure and union.
- In structure we can admission any member in any sequence. Whereas in union we can access only that variable whose value is recently stored.
- All the members can be prepared while declaring the variable of structure. Only first member can be initialized while declaring the variable of union. In above example we can modify only variable roll no at the time of declaration of variable.
- Within a structure all members gets memory allocated and members have addresses that increase as the decelerators are read left-to-right. That is, the members of a structure all begin at different offsets from the base of the structure. For a union compiler allocates the memory for the largest of all members and in a union all members have offset zero from the base, the container is big enough to hold the WIDEST member, and the alignment is appropriate for all of the types in the union.
- Within a structure all members gets memory assigned; therefore any member can be retrieved at any time. While retrieving data from a union the type that is being retrieved must be the type most recently stored.
- One or more members of a structure can be initialized at once. A union may only be initialized with a value of the type of its first member; thus union u described above (during example declaration) can only be initialized with an integer value.
- The amount of memory prerequisite to store a structure variable is the sum of the size of all the members. On the other hand, in case of unions, the amount of memory required is always equal to that required by its largest member.
- With a union, you’re only hypothetical to use one of the elements, because they’re all stored at the same spot. This makes it useful when you want to store something that could be one of several types. A structure, on the other hand, has a separate memory location for each of its elements and they all can be used at once.