How to use unions in c programming language

Follow by Email
Facebook0
Facebook
Google+
https://codingsec.net/2017/04/use-unions-c-programming-language/

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.

Take your time to comment on this article.

Follow by Email
Facebook0
Facebook
Google+
https://codingsec.net/2017/04/use-unions-c-programming-language/

Add a Comment

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

Like the article? please consider sharing it. Thank you

Advertisment ad adsense adlogger