My Blog
Articles related to programming, computer science, technology and research.

23/04/2016 Categories: C Programming. No Comments on Unions in C

Unions have the same syntax as that of a structure since both of them are similar. However, there is a major difference between them in terms of memory allocation. A structure is allocated memory for all the members of the structure whereas a union is allocated memory only for largest member of the union. This implies that, although a union may contain many members of different types, it can handle only one member at a time. Like structure, a union can be declared using the union keyword as shown below:

In the above code student is the name of the union. Also s1 and s2 are union variables. Memory is allocated only for name member of the union. So, the limitation on unions is: only one member can be used at a time. Unions can be used in all places where a structure is allowed.

Below is a C program to demonstrate a union:

In the above program we will only get the correct value 98 for the member s1.marks as in a union only one value can b e used and stored at a time. We will get unexpected values for other members: name and grade.

Suryateja Pericherla

Suryateja Pericherla

Hello, I am Suryateja Pericherla working as an Asst. Professor in CSE department at Vishnu Institute of Technology. I write articles to share my knowledge and make people knowledgeable regarding certain topics.
Suryateja Pericherla

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll Up
Thank you for visiting! If you like this website do share with your friends by clicking on the social icons available on the left hand side.

As the domain name is quite large to remember, use this short domain to visit this site. Short domain: