Union in C Programming Language with Definition and Examples

Union in C Programming Language with Definition and Examples

You will learn about unions in C programming in this lesson. more particularly, how to establish unions, contact members, and understand the distinctions between structures and unions.

With one important exception, a union is a user-defined type that is analogous to structs in C.

In contrast to unions, which can only contain one member value at a time, structures allot adequate room to store all of its members.

Unions in C Programming Language, a data type called union enables the storage of many data types in the same memory regions.

Only one member of the union can be accessed at a time, making it an effective technique to reuse the memory location. A union can be declared and used almost identically to a structure.

You must test the C Language code provided in this lesson in your code editor to validate it. However, if you prefer to execute this code online, we also provide a free C Online Compiler for testing your C Language code.

What is Unions in C?

A Union in C is a user-defined type that is analogous to structs in C. In contrast to unions, which can only contain one member value at a time, structures allot adequate room to store all of its members.

Need for Union in C programming

  • Memory can be saved by using C unions. Consider a union as a section of memory that is used to store variables of various types in order to comprehend it better. The current data gets replaced with new data when we want to assign a new value to a field.
  • Data members that are mutually exclusive can share memory thanks to C unions. When memory is valuable, as it is in embedded systems, this is quite significant. Unions are frequently utilized in embedded programming when direct memory access is required.

Difference between Structure and Union

The primary distinction between a union and a structure is that

  • The space allotted by structures allows them to store all of their fields. The first one is stored at the struct’s beginning, the second one is stored after that, and so on.
  • Unions store all fields in the same location and only allot enough space to store the largest field that is listed.

Defining a Union

Similar to how you did when defining a structure, you must use the union statement to define a union. For your software, the union statement creates a new data type with several members.

The union statement is formatted as follows:

union [union tag] {
   member definition;
   member definition;
   ...
   member definition;
} [one or more union variables]; 

Each member definition is a typical variable definition, such as int I float f, or any other acceptable variable definition, and the union tag is optional. It is optional to specify one or more union variables before the last semicolon at the end of the union specification.

The definition of a union type named Data with the three members a, ft, and str is given below.

union Data {
   int a;
   float ft;
   char str[20];
} data;  

Now, a Data type variable can hold a string of characters, a floating-point value, or an integer. It indicates that several types of data can be stored in a single variable, i.e., the same memory location. Depending on your needs, you can utilize any built-in or user-defined data types inside a union.

A union will have enough space in its memory to accommodate its largest member. For instance, since 20 bytes is the maximum amount of memory that a character string can occupy, Data type will take up 20 bytes in the example above.

The next example illustrates the entire amount of memory utilized by the preceding union.

#include <stdio.h>
#include <string.h>
 
union Data {
   int a;
   float ft;
   char str[20];
};
 
int main( ) {
   union Data data;        
   printf( "Memory size occupied by data : %d\n", sizeof(data));
   return 0;
}

Memory size occupied by data : 20

You can try to test here the example above!

Other example

#include <stdio.h>
struct test1 {
int a, b;
};
union test {
int a, b;
};
int main() {
struct test1 x1={1,2};
union test x;
x.a = 3; 
printf ("after fixing x value the coordinates of a will be %d %d\n\n",x.a, x.b);
x.b = 4; 
printf ("After fixing y value the coordinates of a will be %d %d\n\n", x.a, x.b);
printf("The coordinates of X1 are %d %d",x1.a,x1.b);
return 0;
}

Output of the above example

after fixing x value the coordinates of a will be 3 3
After fixing y value the coordinates of a will be 4 4
The coordinates of X1 are 1 2

None of the fields of a union can be initialized simultaneously. For a structure variable, the output is correct, but for a union variable, the answer appears to be incorrect because a union variable can only contain a single value for each member, i.e., the data is overwritten in the memory.

Clearly, the use case we’ve selected is not suitable for union, but only for struct. This example just serves to explain how union and structure behave.

You can try to test here the example above!

Accessing Union Members

We employ the member access operator to gain access to any union member (.). Between the name of the union variable and the union member that we want to access, the member access operator is coded as a period.

To define variables of the union type, use the term union. The example that follows demonstrates how to use unions in a program.

#include <stdio.h>
#include <string.h>
 
union Data {
   int a;
   float b;
   char str[200];
};
 
int main( ) {
   union Data data_usage;        
   data_usage.a = 10;
   data_usage.b = 220.5;
   strcpy( data_usage.str, "C Programming Language Tutorials");
   printf( "data_usage.a : %d\n", data_usage.a);
   printf( "data_usage.b : %f\n", data_usage.b);
   printf( "data_usage.str : %s\n", data_usage.str);
   return 0;
}

Output of the above example

data_usage.a : 1917853763
data_usage.b : 4122360580327794860452759994368.000000
data_usage.str : C Programming Language Tutorials

Here, we can see that the values of the I and f members of the union were corrupted since the memory region was taken up by the final value allocated to the variable, which is why the value of the str member is being printed so clearly.

You can try to test here the example above!

Let’s examine the identical example once more, this time using one variable at a time, which is the primary benefit of using unions.

#include <stdio.h>
#include <string.h>
 
union Data {
   int a;
   float b;
   char str[200];
};
 
int main( ) {
   union Data data;        
   data.a = 10;
   printf( "data.a : %d\n", data.a);
   
   data.b = 220.5;
   printf( "data.b : %f\n", data.b);
   
   strcpy( data.str, "C Programming Language Tutorials for Beginners");
   printf( "data.str : %s\n", data.str);
   return 0;
}

Output of the above example

data.a : 10
data.b : 220.500000
data.str : C Programming Language Tutorials for Beginners

Here, one member is used at a time, so all of the members print out quite neatly.

You can try to test here the example above!

Summary

We have learned about C unions, their syntax, and usage in this C tutorial. Additionally, we discovered how C unions differ from C structures.

Inquiries

If you have any questions or suggestions about Union in C Programming Language with Definition and Examples, please feel free to leave a comment below.

About Next Tutorial

In the next following post, I’ll create a Bit Fields in C and try to explain its many components in full details. I hope you enjoy this post on Union in C Programming Language with Definition and Examples, in which I attempt to illustrate the language’s core grammar.


Leave a Comment