Home » , » C – Unions

C – Unions

 C – Unions

Structures in C language allow you to store data of different types, whereas Unions allow storing different datatype but in the same memory location.


Unions vs Structures

The Unions and Structures in C language are user-defined datatypes. Let us see the difference:


Definition


Structures in C allow you to store data of different types. The memory for each declared variable in a Structure is allocated to each variable member.


Unions in C allow you to store data of different types, but the memory for the declared variables in a Union is allocated to the largest memory.


Size


The size of the Structure is calculated by adding the sum of its members. Therefore, the size would be greater than or equal to the sum of each member’s size.


The size of the Union is not hard to calculate. It is the size of its largest member.


How to access members?


In Structures, the individual members can be accessed at a time.


In Union, you can access only one member at a time.


Keyword


To define a Structure, use the keyword struct.


To define a Union, use the keyword union.


Create a Union in C

Let us understand the Union concept with an example to define a union. To define a Union, use the union keyword:





Above,

  • The name of the union is Demo,
  • The union members are a, b, c, and d
Let us now see an example and see how many bytes of memory will get allocated in the below program. The largest member of the Union here is double c therefore 8 bytes of memory get allocated and the result would be 8:


Output

Now, let us modify the above example. We have changed the variable d:


Output

Access Union Members

We will see how to access union members in C Language. For this purpose, use the member access operator (.). Let us see an example:


Output




In the above example, the largest member of the Union is char d[20], therefore the bytes of memory get allocated and size 24 can be seen for the largest d variable. Since it is Union, not a Structure, therefore the largest memory occupied by the variable will get considered for the memory allocation. The rest of the variable values are corrupted. This can be fixed by working on one variable at a time as shown below:


Output


In the above example, the corrupted values are now fixed. Rest, the size of the Union is the same, as expected.

If you liked the tutorial, spread the word and share the link and our website LANGUAGE CODING with others.

0 comments:

Post a Comment

Popular Posts

GENRES

 
Copyright ©

latest code update bloggingskillBest coding website in india

Created By Sora Templates | Distributed By Gooyaabi Templates