Structure vs Union in C – Coded Approach

Hello Everyone,

Today we are going to talk a bit about the difference between structure and union as in C programming language.
We are going to provide a coded approach so that you could see the difference practically as the theoretic differences you can read from anywhere on the internet and your text books.

Here comes the code first for the same…

As defined in the code above, we are declaring a student structure first and then an employee union next.
As we know, structure allocates memory for all individual members in it while the union allocates memory only for the largest data unit present in it.
The above difference of memory allocation size is displayed by printing the size of one variable each for struct and union.

Next we display the difference in storage and accessing the members of the two constructs. First we take input for student structure and then for two employee unions. However for the union variables we take the inputs in opposite order. This shows that only one member is accessible at a time. The last input value overrides the previous input value in the union.

A sample output for the program is displayed below:

Rate this post

Leave a Reply