Union in C Programming

Union

Union is a data type with two or more member similar to structure but in this case all the members share a common memory location. The size of the union corresponds to the length of the largest member. Since the member share a common location they have the same starting address.

The real purpose of unions is to prevent memory fragmentation by arranging for a standard size for data in the memory. By having a standard data size we can guarantee that any hole left when dynamically allocated memory is freed will always be reusable by another instance of the same type of union. This is a natural strategy in system programming where many instances of different kinds of variables with a related purpose and stored dynamically.

A union is declared in the same way as a structure.The syntax of union declaration is

 
        union union_name
          {
          type element 1;
          type element 2;
          .......................
          type element n;
         };

This declares a type template. Variables are then declared as:

union union_name x,y,z;

For example, the following code declares a union data type called Student and a union variable called stud:

 
        union student
	     {          
	     int rollno;	 
	     float totalmark;
            };

        union student stud;

It is possible to combine the declaration of union combination with that of the union variables, as shown below.

 
        union union_name
         {
         type element 1;
         type element 2;
         .......................
         type element n;
         }var1,var2,...,varn; 
		 

The following single declaration is equivalent to the two declaration presented in the previous example.

 
        union student
	     {          
	     int rollno;	 
	     float totalmark;
          }x,y,z;
	 

Exercise: Compare structure and Union

Structure:

Ready to get started?

Ready to embark on your journey into the world of C programming? Our comprehensive course provides the perfect starting point for learners of all levels. With engaging lessons, hands-on exercises, and expert guidance, you'll gain the skills and confidence needed to excel in this fundamental programming language. Let's dive in and unlock the endless possibilities of C programming together!