Enums unions C Tutorial

Bodhak enums unions c tutorial & Enums in this Chapter we will discuss Introduction to Unions, Advantages of using unions, a syntax of unions, Difference between Structures and Unions, Nested unions, Writing structure within a union, Writing union within a structure, Introduction to enums, Advantages of using enums, syntax of enums. 

Introduction to Unions: Union is a composite type similar to structure. Even though it has members of different data types, it can hold data of only one member at a time.

 

 

Enums unions C Tutorial

Unions are derived data types and are borrowed from structures by following the same syntax as that of structures

When a union is declared in above manner the amount of memory allocated to the union would be the size of the data item occupying max storage area.

i.e.  name occupies 25 x 1=25bytes

avg occupies = 4 x 1 bytes

int roll occupies = 2 x 1 bytes.

As name occupies 25 bytes the amount of memory allocated in the union declaration would be 25 bytes.

Accessing union members would be same as that of structures.

Over here in the above example, we access the members as,

s1. name;  s2. roll;  s3. avg.

Note:  In a union, the different members share the same memory location.

The total memory allocated to the union is equal to the maximum size of the member.

Since multiple members of different data types have the same location, the data is interpreted according to the type of the member

Advantages of using unions:

When the C compiler is allocating memory for unions it will always reserve enough room for the largest member. i.e unions save memory space.

C provides a facility called typedef for creating new data type names. For example, the declaration

Nested unions:

When we declare one union as a member of another union then we call it as union in union/ Nested union. When we declare the first unit as the member of another union, we call the first unit as child and second as parent union.

 

As in structure within structure and union within structure here also we declare child Union outside the parent union. Only we have to declare a variable of child type union. To access the child union member first provide the parent union name followed by dot(.) followed by child union name followed by dot(.) followed by member name.