Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Understanding 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?
11.
Conclusion
Last Updated: Mar 27, 2024
Easy

Union in C

Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

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.

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

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

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;
}

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

Feature C Union C Structure
Memory Allocation Shares memory space among all members. Each member has its memory space.
Memory Usage Shares memory, using the largest member's size. Requires memory for each member simultaneously.
Accessing Members Members share the same memory space. Members are accessed individually.
Size Calculation Size is the size of the largest member. Size is the sum of sizes of its members.
Memory Wastage No wastage as it uses the size of the largest member. Can lead to memory wastage for small types.
Initialization All members share the same memory, so initializing one affects others. Each member can be initialized separately.
Usage Suitable when only one of the data types is used at a time to save memory. Suitable when different data types are needed.
Example c 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.

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.

Related Articles: Bit stuffing program in c

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. 

Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Live masterclass