Skip to main content

Union in C

C Programming: The Efficiency of Unions

Imagine owning a single, small storage locker. You can put a bicycle inside it, or you can stack several moving boxes inside it, but you absolutely cannot fit both at the same time. If you decide to store the bicycle, you must remove the boxes first.

In C programming, a Union works exactly like this single storage locker. While a struct provides separate storage spaces for every single piece of data, a union forces all its members to share one exact memory location. Programmers use unions to save massive amounts of memory when they know a variable will only ever hold one type of data at a time.

1. What is a Union?

You declare a union almost exactly identically to a structure, utilizing the union keyword instead of struct. However, the way the computer handles them behind the scenes differs completely.

// Creating the Union blueprint
union Data {
    int i; // Requires 4 bytes
    float f; // Requires 4 bytes
};

// Building the actual union variable
union Data myData;

2. Deep Dive: Memory Sharing

The entire purpose of a union is Memory Sharing. When the compiler reads your union blueprint, it scans all the members to find the largest one. It then reserves just enough memory to fit that single largest member. All other members simply share that exact same physical space.

Real-life example: A factory operates 24/7. John works the day shift, and Mark works the night shift. The company assigns them the exact same desk and computer. They share the space, but they never occupy it simultaneously. If John leaves his day-shift notes on the desk, Mark will clear them away when he arrives for the night shift.

Because they share memory, modifying one member instantly overwrites the others. Let us look at a code example to prove this behavior:

#include <stdio.h>

union Data {
    int i;
    float f;
};

int main() {
    union Data myData;

    // We store an integer
    myData.i = 100;
    printf("Integer assigned: %d\n", myData.i);

    // We overwrite the shared memory with a float
    myData.f = 99.5;
    printf("Float assigned: %.1f\n", myData.f);

    // Now, we try to print the integer again
    printf("Attempting to print Integer again: %d\n", myData.i); // Prints garbage!

    return 0;
}

In the code above, the moment we assign the float (99.5), the integer (100) gets destroyed because the float overwrites the binary data in that shared memory block. Reading the integer afterward yields unpredictable garbage data.

3. Difference Between Structure and Union

Structures and unions look identical in code, but they serve entirely different purposes. We use structures to bundle related data together simultaneously. We use unions to restrict a variable to holding only one specific piece of data at any given time, saving RAM.

Feature Structure (struct) Union (union)
Memory Allocation The compiler allocates separate, unique memory for every single member. The compiler allocates one shared block of memory based on the largest member.
Data Access You can access and manipulate all members simultaneously without data loss. You can strictly access only one member at a time.
Total Memory Size The size equals the sum of all members combined (plus some minor padding). The size equals the size of the single largest member inside the union.
Overwriting Altering the value of one member does not affect any other members. Altering the value of one member entirely overwrites the data of the others.
Primary Use Case Used for creating complex records (like a Student with an ID, Name, and Grade). Used in embedded systems and hardware programming to aggressively save RAM.

Summary: Unions in C

  • A union forces multiple variables to share the exact same physical memory address.
  • Because members share memory, a union can only hold a valid value for one member at a time.
  • The total size of a union is determined by the single largest data type defined inside it.
  • Writing to one member of a union actively corrupts the data stored by previous members.
  • Programmers primarily use unions in low-level systems (like microcontrollers) where every single byte of RAM is precious.

C Programming Interview Questions (FAQs)

1. How exactly does the compiler calculate the size of a union?

The compiler scans the union's blueprint and identifies the data type that demands the most space. For example, if your union contains a 1-byte char, a 4-byte int, and an 8-byte double, the compiler will set the entire union's size to exactly 8 bytes. All three members will take turns squeezing into that same 8-byte space.

2. Can I initialize all members of a union at the exact same time?

No, you cannot. When you initialize a union using curly braces (e.g., union Data d = {10};), the C compiler strictly assigns that value to the very first member defined in your blueprint. Because memory overlaps, attempting to assign multiple values at birth simply overwrites the previous values.

3. When would a professional developer actually choose a union over a structure?

Developers use unions in environments with extreme memory constraints, such as programming IoT devices or embedded microcontrollers. They also use them heavily in network programming. A network packet might arrive as either an IPv4 packet, an IPv6 packet, or an Error packet. Since a single packet cannot be all three at once, developers store the incoming data in a union to prevent wasting memory on the two unused packet formats.

Comments

Popular posts from this blog

How I Got Selected in MNC

Virtusa Sometimes success does not come from having the best coding skills or the perfect roadmap. Sometimes it comes from simply refusing to quit. This is the honest story of how I transitioned from a confused, rejected fresher to getting selected as an Associate Engineer at Virtusa. The Beginning: Confused About My Future After completing my graduation, I stared blankly at my career options. Like many freshers, I lacked a clear direction. Should I join a Java course? Should I prepare on my own? Should I just wait for campus placement opportunities? One day, I called my friend Chetan. He suggested I join Naresh i Technologies and start learning Java seriously. Still unsure of my path, I told him I needed time to think about it. A couple of days later, my phone buzzed with a WhatsApp message offering a job opportunity. They asked me to come for the next round of the recruitment process. Excitement completely took over. I packed my bags, traveled to th...

Spring Boot Introduction

Spring Boot Introduction: Architecture, Dependencies, and Embedded Servers Modern enterprise applications demand rapid development, frictionless deployment, and absolute minimal configuration. Before Spring Boot arrived, developers utilizing the Spring Framework wasted immense amounts of time configuring XML files, managing clashing dependencies, setting up clunky application servers, and stitching various Spring modules together manually. To eliminate these bottlenecks, Pivotal introduced Spring Boot . Built entirely on top of the traditional Spring Framework, Spring Boot is an "opinionated" framework. It aggressively simplifies application development by injecting auto-configuration, packaging starter dependencies, and embedding web servers directly into your application. This allows backend developers to focus entirely on building business logic rather than wrestling with infrastructure setup. What is Spring Boot? Spring Boot is a powerful extens...

Data Types in C

C Programming: Understanding Data Types Think of your kitchen. You store a large bag of flour in a big bin, a pinch of saffron in a tiny jar, and milk in a liquid measuring jug. You do not put liquids into paper bags, and you do not use a massive bucket for a single teaspoon of sugar. C programming works the exact same way. When you create a variable, you must tell the computer exactly what kind of "container" to build in its memory. We call these containers Data Types . They dictate what kind of data the container holds, how much space it takes up, and what operations you can perform on it. 1. Primitive Data Types C offers several built-in, "primitive" data types. Think of these as the fundamental storage containers. int (Integer): You use this to store whole numbers without decimals. Real-life example: Counting the number of people in a room or tracking a player's score in a video game. char (Character): You use this ...