Unions in C

Challenge Inside! : Find out where you stand! Try quiz, solve problems & win rewards!

Learn via video course

C++ Course: Learn the Essentials
C++ Course: Learn the Essentials
By Prateek Narang
Free
star5
Enrolled: 1000
C++ Course: Learn the Essentials
C++ Course: Learn the Essentials
Prateek Narang
Free
5
icon_usercirclecheck-01Enrolled: 1000
Start Learning

Overview

In C, a union is a user-defined data type that allows many different data types to be stored in the same memory region. A union can have numerous members, but only one of them can occupy the memory at any one moment. Unions allow developers to optimize memory usage while declaring variables.

Scope of this article

In this article, we shall see:

  • What are unions?
  • How to declare and use them in C
  • How to access members of a union
  • Examples and applications of unions
  • The differences between structures and unions

Introduction

Imagine an e-commerce company that wants to keep track of all products that it wants to sell. At the most basic level, it would like to keep track of the details of the products it's selling and shipping.

Each product contains defined properties like weight, dimensions and price. Furthermore, to store details of each product, memory space is required in the computer systems at every warehouse of the company across the country or the world. When we consider the size and numbers at which a multinational e-commerce country operates, it becomes clear that the amount of memory space needed to store the details of each product needs to be optimized without compromising the integrity of the data.

The concept of unions takes shape to help with situations such as these, where related data needs to be stored in a memory-optimized way.

As mentioned above, unions are user-defined data type that allows many different data types to be stored in the same memory region. This essentially means that one data member can have its data stored in the memory at a time, and changing the value of any union member affects the data stored in the memory. Let us now look at how unions can be used in C.

How to Declare a Union?

We must use the union keyword to declare a union the same way we use the struct keyword to declare a structure. We use unions to define a data type with more than one different member to use in our program. The syntax is as follows:

The unionName is optional, but it is best practice to have one. If not using unionName results in anonymous unions. These are usually nested inside struct and use the struct's name to identify them.

An example of an anonymous union is:

Output:

Member definitions include the regular variable declarations, like int a or char ch. Finally, we can declare one or more union variables at the end of the union, right after the '}' and before the ';'. The union variables provide an expressway to use the union in our program, i.e., instead of declaring the entire union, we can use the unionVar to use the union in the program. These are, however, optional.

Ways to define Union Variables in C

One way of defining a union without using union variables is as follows:

Another way of defining a union, using union variables, is as follows:

In both cases, two union variables circle1 and circle2 are created.

Accessing Union Data Members

A union variable can either be an object or a pointer. Based on that, there are two ways to access union data members:

  • If the union variable is a pointer, use the arrow pointer (->).
  • Using the dot (.) operator, if the union variable is an object.

Let’s see how this works through an example:

Output:

What we’ve done above is essentially created a pointer variable p and two union objects x and t. Pointer p stores the address of the variable x. Now we can access the data member a of the union using the pointer p with the help of the arrow (->) operator. And, the data memberb can be accessed using the union object t with the help of the dot (.) operator. Hence, the above code gives the value of a as 500, and b as Hello.

Example of a Union in C

Output:

We have taken 2 of them in the above program to understand how values are stored in union variables.

In record 1, First, the memory of union doc1 contains the value 2234 corresponding to the int data type. Next, when the union member doc1.name has been assigned the value 'Ravi Krishna', the memory location name is now doc1.name, and the value stored in this location is 'Ravi Krishna' corresponding to the char[] data type.

Next, the union member doc1.department has been assigned the value 'Radiology'. The memory location has been changed to doc1.department and the value to 'Radiology', also corresponding to the char[] data type. Keep in mind unions can hold only one member at a time.

Therefore, the values in the shared memory are constantly being replaced every time a new member is assigned a value. Thus when the value in doc1.id is printed, a garbage value appears in the Output as the shared memory is held by the char[] datatype. Also, the value printed by name and department is the same as they are of char[] type.

The values of Record 2 appear correctly at the Output. This is because the union members' values are printed before their address and values are changed.

How the Compiler defines the Size of a Union in C?

A union's memory will be vast enough to store the union's largest member. It makes no difference what is in use right now.

To understand what this means in detail, let's take the following code as an example:

Output:

Here, we see that the size of union unionA is 4. This is because both the data members are of type int whose size is 4. Similarly, the size of union unionB is also 4, since the size of the largest data member in the union unionB, i.e., int is 4. When it comes to union unionC. The char data member has size 1 byte and the integer array has size 10 * 4 = 40, which makes the size of unionC = max(1, 40) = 40.

Applications of Union

  • Unions are used when mutually exclusive data members have to share the memory in places where memory space is at a premium, such as embedded systems.
  • Unions are also used when the program needs direct memory access.

To further understand their applications, let's take up an example:

Imagine a two-wheeler dealership that sells motorbikes and bicycles. The dealership owner would like to keep track of the inventory of the items in his establishment and store the relevant information in a computer system. The motorcycle has a price, engine size, and mileage, whereas the bicycle has the properties of color and price. The property of price is common to both items. The shop owner would now like to store them as records.

One thing the owner can do is to store the records in a structure, such as:

But now, if we were to store the record of a bicycle, then it would only contain the properties of color and price. It won’t have the properties of engineSize and mileage, hence completely wasting space.

If, however, we were to use unions inside of a structure, then the record would look something like this;

In the code above, we have created an object of type records. We have used a union to store values. Hence the value of the largest member in the union is by default the maximum size of the union. This way, we save valuable memory space by not having to unnecessarily declare space for properties that have no relation to the product.

Differences between Structures and Unions

To differentiate between structures and unions, let’s take an example:

OUTPUT:

The reason for this is that in sFood:

  • Size of name is 32 bytes
  • Size of cost is 4 bytes
  • Size of fid is 4 bytes

Bringing the total size to 40 bytes.

However, in unions, all members share the same memory, and the size of memory assigned is equal to the largest member. Here in uFood, the name has the largest size (32 bytes). Hence the size of the entire union is 32 bytes.

Some other differences between structures and unions include:

  • Altering the members' values in the struct will not affect the other members. However, altering members' values in unions will affect the other members.
  • In structures, every member is assigned a unique memory location, whereas, in unions, all the data members share a memory location.
  • In structures, individual members can be accessed at any time. In unions, however, only one member can be accessed simultaneously.
  • In structures, several or all members can be initialized at once. However, in unions, only the first union member can be initialized.

Conclusion

In this article,

  • We’ve explored the concept of unions in C.
  • We have seen its syntax, functions, declarations, and how it operates.
  • We have also seen the difference between unions and structures with examples.