The Wayback Machine - https://web.archive.org/web/20250210121525/https://www.geeksforgeeks.org/c-unions/
Open In App

C Unions

Last Updated : 10 Jan, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

In C, union is a user-defined data type that can contain elements of the different data types just like structure. But unlike structures, all the members in the C union are stored in the same memory location. Due to this, only one member can store data at the given point in time.

Let’s take a look at an example:

C
//Driver Code Starts{
#include <stdio.h>
#include <string.h>

//Driver Code Ends }

// Union definition
union A {
    int i;
    float f;
    char s[20];
};

int main() {
  
    union A a;

    // Storing an integer
    a.i = 10;
    printf("data.i = %d
", a.i);

    // Storing a float
    a.f = 220.5;
    printf("data.f = %.2f
", a.f);

    // Storing a string
    strcpy(a.s, "GfG");
    printf("data.s = %s
", a.s);

//Driver Code Starts{

    return 0;
}
//Driver Code Ends }

Output
data.i = 10
data.f = 220.50
data.s = GfG

In this article, we will learn about union type in C, its syntax, working and some common use cases with examples.

Syntax of Union in C

The syntax of union can be defined into two parts:

C Union Declaration

In this part, we only declare the template of the union, i.e., we only declare the members’ names and data types along with the name of the union. No memory is allocated to the union in the declaration.

union name {
type1 member1;
type2 member2;
.
.
};


Create a Union Variable

We need to define a variable of the union type to start using union members. There are two methods using which we can define a union variable:

Creating Union Variable with Declaration

union name{
type member1;
type member2;
…
} var1, var2, …;

Creating Union Variable after Declaration

union name var1, var2, var3…;

where name is the name of an already declared union.

Access Union Members

We can access the members of a union by using the ( . ) dot operator just like structures.

var1.member1;

where var1 is the union variable and member1 is the member of the union.

Initialize Union

The initialization of a union is the initialization of its members by simply assigning the value to it.

var1.member1 = val;

One important thing to note here is that only one member can contain some value at a given instance of time.

Size of Union

The size of the union will always be equal to the size of the largest member of the union. All the less-sized elements can store the data in the same space without any overflow. Let’s take a look at the code example:

C
#include <stdio.h>

// Declaring multiple unions
union A{
    int x;
    char y;
};

union B{
    int arr[10];
    char y;
};


int main() {

    // Finding size using sizeof() operator
    printf("Sizeof A: %ld\n", sizeof(union A));
    printf("Sizeof B: %ld\n", sizeof(union B));
  
    return 0;
}

Output
Sizeof A: 4
Sizeof B: 4
Sizeof C: 40

The above unions’ memory can be visualized as shown:

Nested Union

In C, we can define a union inside another structure or union. This is called nested union and is commonly used when you want to efficiently organize and access related data while sharing memory among its members.

Syntax

struct/union … {
mem1…
union name {
type1 member1
type2 member2
.
.
}nested_member_name;
};

As we can see, we have to create a variable of the nested union for it to be usable. Due to this, we can also skip name of the union and only name a variable of it. This type of unions are called Anonymous Unions.

Access Nested Union Member

The union members can be accessed using dot operator, but we have to use it multiple times:

outer_union . inner_union . member

Let’s take a look at a nested union example:

C
#include <stdio.h>

// Define a structure containing a nested union
struct Employee {
    char name[50];
    int id; 

    union {
          
          // Hourly rate for part-time employees
        float hourlyRate;
      
           // Monthly salary for full-time employees
        float salary;    
    } payment;
};

int main() {
    struct Employee e1;

    // Assign details for a part-time employee
    snprintf(e1.name, sizeof(e1.name), "Rahul");
    e1.id = 101;
    e1.payment.hourlyRate = 300;


    printf("Employee 1: %s (ID: %d)\n", e1.name, e1.id);
    printf("Hourly Rate: Rs %.2f", e1.payment.hourlyRate);


    return 0;
}

Output
Employee 1: Rahul (ID: 101)
Hourly Rate: Rs 300.00

Structure vs Union

The following table lists the key difference between the structure and union in C:

StructureUnion
The size of the structure is equal to or greater than the total size of all of its members.The size of the union is the size of its largest member.
The structure can contain data in multiple members at the same time.Only one member can contain data at the same time.
It is declared using the struct keyword.It is declared using the union keyword.

C Unions – FAQs

What is the size of the given union?

C
union un {
int a;
int arr[20];
}

The size of the given union is 20 x 4 bytes = 80 bytes. Even if the array is a collection of similar data elements, it is considered to be a single entity by the C compiler.

Can we store data in multiple union members at the same time?

No. We can only store data in a single member at the same time. For example in the following C program, both x and y share the same location. If we change x, we can see the changes being reflected in y. 

C
#include <stdio.h>

// Declaration of union is same as structures
union test {
    int x, y;
};

int main(){
    // A union variable t
    union test t;

    t.x = 2; // t.y also gets value 2
    printf("After making x = 2:\n x = %d, y = %d\n\n", t.x,
           t.y);

    t.y = 10; // t.x is also updated to 10
    printf("After making y = 10:\n x = %d, y = %d\n\n", t.x,
           t.y);
    return 0;
}

Output
After making x = 2:
 x = 2, y = 2

After making y = 10:
 x = 10, y = 10

What are the applications of unions?

Unions can be useful in many situations where we want to use the same memory for two or more members. For example, suppose we want to implement a binary tree data structure where each leaf node has a double data value, while each internal node has pointers to two children, but no data. If we declare this as: 

C
struct NODE {
    struct NODE* left;
    struct NODE* right;
    double data;
};

then every node requires 16 bytes, with half the bytes wasted for each type of node. On the other hand, if we declare a node as the following, then we can save space. 

C
struct NODE {
    bool is_leaf;
    union {
        struct {
            struct NODE* left;
            struct NODE* right;
        } internal;
        double data;
    } info;
};


Next Article

Similar Reads

three90RightbarBannerImg