Table of contents
1.
Introduction
2.
What is Union in C?
3.
Syntax of Union in C
3.1.
C Union Declaration
4.
Different Ways to Define a Union Variable
4.1.
With Union Declaration
4.2.
After Union Declaration
5.
Initialization of Union in C
6.
Example of Union in C
6.1.
C
7.
Size of Union
8.
Difference between C Union and C Structure
9.
Future of Union in C
10.
Frequently Asked Questions
10.1.
What are the applications of unions?
10.2.
What is the size of the given union?
10.3.
Can we store data in multiple union members at the same time?
10.4.
What is the difference between structure and union?
10.5.
Why structure is better than union?
11.
Conclusion
Last Updated: Dec 23, 2024
Easy

Union in C

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

The C programming language is known for its power and flexibility, allowing developers to manage memory, data, and processes with a high degree of control. Among its arsenal of features, the union data type stands as a unique construct, allowing multiple data types to share the same memory location. 

union in c

This article elucidates the concept of unions in C, discussing its benefits, drawbacks, practical applications, and its place in the future of programming.

What is Union in C?

Unions in C are a user-defined data type that permits different data types to be stored in the same memory location. While similar to structures, the key difference is that all members of a union occupy the same memory location, which means only one member can store a value at a time. Unions are primarily used when you need to work with different data types in the same memory space to save memory.

Syntax of Union in C

Here is a basic syntax to declare a union:

union Data {
   int i;
   float f;
   char str[20];
};

In this union named Data, an integer, a float, and a character array share the same memory space. At any given time, only one of them can hold a value.

C Union Declaration

In C, you declare a union using the union keyword. Here's the general syntax:

union union_name {
   // member declarations
};

Different Ways to Define a Union Variable

There are two ways to define a union variable:

With Union Declaration

union name_of_union {
    datatype member;
} var;

 

This code defines a union named name_of_union with a single member of data type datatype. The union is named var, and it can hold data of the specified data type in its member. 

After Union Declaration

union name_of_union var;

 

In this code, name_of_union is the name of an already declared union.

Initialization of Union in C

The union is initialized by assigning values to its members. It's essential to note that, at any given moment, only one member can hold a value.

var.member = some_value;

Example of Union in C

  • C

C

#include <stdio.h>

// Define a union named MyUnion
union MyUnion {
int intValue;
float floatValue;
char stringValue[20];
};

int main() {
// Declare an instance of the union
union MyUnion data;

// Assign values to different members of the union
data.intValue = 42;
printf("Integer Value: %d\n", data.intValue);

data.floatValue = 3.14;
printf("Float Value: %.2f\n", data.floatValue);

// Assign a string to the union
strcpy(data.stringValue, "Hello, Union!");
printf("String Value: %s\n", data.stringValue);

return 0;
}
You can also try this code with Online C Compiler
Run Code

Explanation:

In this example, the union MyUnion has three members: intValue of type int, floatValue of type float, and stringValue of type character array. The program demonstrates how to use these members and shows that they share the same memory space.

Output:

output

Size of Union

The size of a union in C is determined by the size of its largest member. The idea is that all members of a union share the same memory space, so the union's size needs to be large enough to accommodate its largest member.

Difference between C Union and C Structure

FeatureC UnionC Structure
Memory AllocationShares memory space among all members.Each member has its memory space.
Memory UsageShares memory, using the largest member's size.Requires memory for each member simultaneously.
Accessing MembersMembers share the same memory space.Members are accessed individually.
Size CalculationSize is the size of the largest member.Size is the sum of sizes of its members.
Memory WastageNo wastage as it uses the size of the largest member.Can lead to memory wastage for small types.
InitializationAll members share the same memory, so initializing one affects others.Each member can be initialized separately.
UsageSuitable when only one of the data types is used at a time to save memory.Suitable when different data types are needed.
Examplec union Number { int x; float y; };c struct Point { int x; int y; };

Future of Union in C

Unions continue to hold their ground as a useful construct in C, especially in memory-constrained environments or systems-level programming. However, with the evolution of high-level languages offering more built-in safety features, the usage of unions might be seen as arcane or risky, pushing developers towards safer alternatives.

Also see, odd or even program in c

Frequently Asked Questions

What are the applications of unions?

Unions are useful when different data types share the same memory space, often used in low-level programming for efficient memory usage.

What is the size of the given union?

The size of a union is determined by the size of its largest member.

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

In a union, only one member can hold a value at a time. Writing to one member may overwrite the value in another member.

What is the difference between structure and union?

In a structure, each member has its own memory location, allowing all members to store values simultaneously; the total size is the sum of all members. In a union, all members share the same memory location, so only one member can hold a value at a time.

Why structure is better than union?

Structures are better than unions when storing multiple values simultaneously, as each member has its own memory, ensuring data integrity. Unions, sharing memory among members, overwrite previous data, risking loss. Structures are ideal for managing complex, independent data, while unions excel in memory-efficient tasks for specialized, low-level programming.

Conclusion

Unions in C provide a unique way to work with data, offering memory efficiency and flexibility at the cost of potential data corruption and increased complexity. As we advance into an era of programming where memory is abundant and safety is a priority, the use of unions may dwindle. However, in systems programming and memory-constrained environments, the utility of unions continues to shine, marking them as an enduring feature of the C programming language.

Live masterclass