C Unions - GeeksforGeeks (2024)

Last Updated : 04 Sep, 2023

Improve

The Union is a user-defined data type in C language 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 instance.

C Unions - GeeksforGeeks (1)

Syntax of Union in C

The syntax of the union in C can be divided into three steps which are as follows:

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 union_name { datatype member1; datatype member2; ...};

Keep in mind that we have to always end the union declaration with a semi-colon.

Different Ways to Define 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.

  1. With Union Declaration
  2. After Union Declaration

1. Defining Union Variable with Declaration

union union_name { datatype member1; datatype member2; ...} var1, var2, ...;

2. Defining Union Variable after Declaration

union union_name var1, var2, var3...;

where union_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.

The above method of accessing the members of the union also works for the nested unions.

var1.member1.memberA;

Here,

  • var1 is a union variable.
  • member1 is a member of the union.
  • memberA is a member of member1.

Initialization of Union in C

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

var1.member1 = some_value;

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

Example of Union

C

// C Program to demonstrate how to use union

#include <stdio.h>

// union template or declaration

union un {

int member1;

char member2;

float member3;

};

// driver code

int main()

{

// defining a union variable

union un var1;

// initializing the union member

var1.member1 = 15;

printf("The value stored in member1 = %d",

var1.member1);

return 0;

}

Output

The value stored in member1 = 15

Size of Union

The size of the union will always be equal to the size of the largest member of the array. All the less-sized elements can store the data in the same space without any overflow.

C Unions - GeeksforGeeks (2)

Memory Allocation in C Union

Example 1: C program to find the size of the union

C

// C Program to find the size of the union

#include <stdio.h>

// declaring multiple unions

union test1 {

int x;

int y;

} Test1;

union test2 {

int x;

char y;

} Test2;

union test3 {

int arr[10];

char y;

} Test3;

// driver code

int main()

{

// finding size using sizeof() operator

int size1 = sizeof(Test1);

int size2 = sizeof(Test2);

int size3 = sizeof(Test3);

printf("Sizeof test1: %d\n", size1);

printf("Sizeof test2: %d\n", size2);

printf("Sizeof test3: %d", size3);

return 0;

}

Output

Sizeof test1: 4Sizeof test2: 4Sizeof test3: 40

Difference between C Structure and C 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.

FAQs on C Unions

1. What is the size of the given union?

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

Ans: 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.

2. 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

// C program to check if we can store data in multiple union

// members

#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 = 2After making y = 10: x = 10, y = 10

3. 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;

};



C Unions - GeeksforGeeks (3)

GeeksforGeeks

Improve

Previous Article

Flexible Array Members in a structure in C

Next Article

Bit Fields in C

Please Login to comment...

C Unions - GeeksforGeeks (2024)

FAQs

C Unions - GeeksforGeeks? ›

The Union is a user-defined data type in C language 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 instance.

What are unions in C? ›

Union is an user defined datatype in C programming language. It is a collection of variables of different datatypes in the same memory location. We can define a union with many members, but at a given point of time only one member can contain a value.

How are C structures different from unions? ›

The difference between structure and union in C is analogous to the distinction between multi-slot and single-slot vending machines. While structures in C allow for storing multiple data types concurrently, unions prioritize space efficiency, storing only one data type at a time.

What is union in C Tutorialspoint? ›

A union is a special data type available in C that allows to store different data types in the same memory location. You can define a union with many members, but only one member can contain a value at any given time. Unions provide an efficient way of using the same memory location for multiple purpose.

What are unions in C ++? ›

A union in C++ is a data structure that allows different data types to be stored in the same memory location. Unlike structures, unions share memory, enabling efficient memory usage.

What are the advantages of union in C programming? ›

With C unions, a programmer can save memory and operate with multiple variables using one union instance. This is beneficial for both writing code and optimizing data usage. Unions enable programmers to access data via different types of variables, which prevents accidental type errors.

What are the use cases of unions in C? ›

Typical Use Cases

One common use case of unions is in managing different data types that might not be known until runtime. They are also used in hardware register access, where the register might contain different types of information at different times.

What are the 4 structures or types of unions? ›

There are a variety of sizes, structures, and types of unions such as local unions, national unions, craft unions, and industrial unions.

How to compare two unions in C? ›

For compare union you have to write some code like this one: all_integer union1; all_integer union2; /*To ensure all the unused data of the unions are the same, it's necessary to set unions, before to use it, at the same value (0 in this case).

What is a C pointer? ›

The pointer in C language is a variable which stores the address of another variable. This variable can be of type int, char, array, function, or any other pointer. The size of the pointer depends on the architecture. However, in 32-bit architecture the size of a pointer is 2 byte.

Do all the union members have separate memory? ›

In union, the total memory space allocated is equal to the member with largest size. All other members share the same memory space. This is the biggest difference between structure and union.

How to calculate size of union in C? ›

  1. Define the union named sample.
  2. Declare three variables m, n and ch of different data types.
  3. Use the keyword sizeof() to find the size of a union and print the same.
  4. Initialize each variable with some value and print its value as output.
  5. Exit.

What is an algorithm in C? ›

An algorithm is a step-by-step procedure to solve a given problem. In the context of computer science, particularly with the C programming language, an algorithm is used to create a solution that computers can understand and execute.

How do C unions work? ›

Union is a data type in C programming that allows different data types to be stored in the same memory locations. Union provides an efficient way of reusing the memory location, as only one of its members can be accessed at a time.

Which is better structure or union? ›

Structures are better for consistent performance and should be used when working with a variety of data types. When working with a large number of members or objects, unions are more appropriate. Unions are better for cases when two or more members need to share the same memory location.

What is union example? ›

A union in math is a when two or more sets combine and the resulting set contains all of the elements present in each set. For example, if set A = {4, 7, 9, 3, 10} and set B = {1, 4, 10, 11, 20} the union of sets A and B, written as A ∪ B , results in the set A ∪ B = {1, 3, 4, 7, 9, 10, 11, 20}.

What are unions used for? ›

A union is an organization formed by workers who join together and use their strength to have a voice in their workplace. Through their union, workers have the ability to negotiate from a position of strength with employers over wages, benefits, workplace health and safety, job training and other work-related issues.

What is union and intersection in C? ›

The union of two arrays results in a new array that contains all the distinct elements from both arrays, while the intersection of two arrays yields a new array that contains only the common elements between the two arrays.

What is a union example? ›

What Are Examples of Labor Unions? Trade unions represent workers who do a particular type of job. The American Federation of Labor-Congress of Industrial Organizations (AFL-CIO) is a trade union. Industrial unions represent workers in a particular industry, such as the National Education Association (NEA).

What is union in C W3schools? ›

Union is a user-defined data type in C, which stores a collection of different kinds of data, just like a structure. However, with unions, you can only store information in one field at once.

References

Top Articles
Latest Posts
Article information

Author: Delena Feil

Last Updated:

Views: 5529

Rating: 4.4 / 5 (65 voted)

Reviews: 88% of readers found this page helpful

Author information

Name: Delena Feil

Birthday: 1998-08-29

Address: 747 Lubowitz Run, Sidmouth, HI 90646-5543

Phone: +99513241752844

Job: Design Supervisor

Hobby: Digital arts, Lacemaking, Air sports, Running, Scouting, Shooting, Puzzles

Introduction: My name is Delena Feil, I am a clean, splendid, calm, fancy, jolly, bright, faithful person who loves writing and wants to share my knowledge and understanding with you.