Open In App

How to Use a Union to Save Memory in C?

Last Updated : 13 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Unions in C offer a unique mechanism for storing different variables in the same memory location. These variables are called members of the union and can be of different types as well. In this article, we will learn how to use a union to save memory in C.

Save Memory using Union in C

Union members share the same memory space with the size of this space being the size of the largest data member. This property of union helps us to reduce memory consumption in situations where only one variable will store data at some point in time.

But we have to be careful while using a union as only a single member can store information at a time and accessing other members may lead to undefined behavior.

C++ Program to Use Union for Saving Memory

The below example demonstrates the use of union to save the memory.

C




// C++ program to use union to save memory
  
#include <stdio.h>
#include <string.h>
// define the Union
union MutuallyExclusiveData {
    int intValue;
    float floatValue;
    char stringValue[20];
};
int main()
{
    // declare a Union Variable
    union MutuallyExclusiveData data;
  
    // set Values for Different Types
    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 same memory location
    strcpy(data.stringValue, "Hello, Union!");
    printf("String value: %s\n", data.stringValue);
  
    // accessing Values
    printf("After string assignment, Integer value: %d\n",
           data.intValue);
  
    return 0;
}


Output

Integer value: 42
Float value: 3.14
String value: Hello, Union!
After string assignment, Integer value: 1819043144

Explanation: The above example shows how we can save memory using a MutuallyExclusiveData union, which can hold different types of data like integers, floats, and strings, but only one at a time. Since only one data type is used at any moment, the union shares memory among its members. This way, it only uses as much memory as the biggest member needs, making it more memory-efficient.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads