Union in C programming

Union in C

Union in C is user defined data types which is used to store data having different data types and combine them in a single unit. Union in C works similar to structure but there are some differences between them. It creates a single memory storage for all data member. The memory is shared by all data member. It is capable of handling all data member (one at a time).

“HOW TO DECLARE UNION IN C”

Union in C is declared using the keyword union followed by tag_name like structure is declared using keyword struct.

Syntax:

 

The object or variable of a union can be created within main function and also it can be created by providing variable name at the end of closing bracket followed by semi-colon. As shown below:

(Creating the object of union by providing variable name at the end of definition)

NOTE: All programs are compiled in Dev C++ compiler.

Creation object of the union inside the main function.

Similarly we can create number of variables or object by following any of the method discussed above.

OUTPUT:

Description:

  • Carefully observe the output of above program. You might have observed value of variable roll has corrupted or misprint. Have you thought why this  happened? OK, I will let you know.Kindly go through the picture given below:

Union in C

  • So I think you have got the answer. Yes, this is because the variable admn and roll are sharing same memory location for storing their value. In union all the data member shared same memory so the value which is stored last, overrides the existing variable and changes the value. Here the value entered for admn variable overrides the value of roll.

WHAT WILL BE THE SIZE OF UNION?

The size of the union will be the size of largest data member. You can also check the size of union using sizeof() operator.

OUTPUT:

Here you have observed the size of union is 20 bytes.The size of character array “name” is 20 byte which is larger than roll. Hence the size of union is 20 bytes.

Click here to appear Quick Solution Online test.

            

Leave a Reply