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

Strings in C

C Programming: Working with Strings Unlike modern programming languages like Python or Java, C does not possess a dedicated "String" data type. Instead, C treats a string as a simple 1D array of characters. Real-life example: Think of a freight train. The train does not exist as one solid object; it consists of individual boxcars linked together. Similarly, a C string links individual characters side-by-side in memory. To let the computer know the train has ended, C attaches a special "caboose" called the Null Terminator ( \0 ). 1. Essential String Functions Handling strings manually requires complex loops. To save time, C provides a built-in library called <string.h> that contains powerful functions to manipulate text. strlen(): You use this to find the exact length of a string. The compiler counts the characters until it hits the \0 terminator. It does not count the terminator itself. strcpy(): You use...

Graph Algorithms

Graph Algorithms: Navigating Complex Networks Graphs represent the absolute pinnacle of data structure interview questions for top-tier tech companies. Why? Because the modern digital world runs entirely on graph networks. When you search for the fastest route on Google Maps, you traverse a graph of cities and roads. When you view friends on Facebook or connections on LinkedIn, you query a graph of users. Even the underlying architecture of Git commits, internet routers, and microservice dependencies rely purely on graph theory. 1. What is a Graph? A graph abandons the strict top-down hierarchy of a Tree. Instead, it forms a free-flowing network built from two core components: Vertices (Nodes): The actual data points in the network (e.g., specific cities, or specific users). Edges: The physical or logical connections linking those nodes together (e.g., the highways between cities). Graph Terminology & Types To manipulate graphs effici...

Programming For Problem Solving

What are General Problem-Solving Concepts? Problem-solving is an important skill at both the personal and professional levels. People make decisions to solve a problem. Whether you’re fixing a leaking faucet at home or troubleshooting complex technical issues on a computer, the ability to effectively troubleshoot challenges is invaluable. In this comprehensive tutorial, we’ll delve into the troubleshooting mindset, general availability, and its practical applications in the computer industry. By breaking down the process into manageable steps and providing technical examples, we aim to equip readers with the tools to solve problems practically and confidently. Total Steps for Problem Solving: 1. Identifying the Problem The fundamental principle of problem-solving lies in accurately identifying the issue at hand. This involves understanding the signs and figuring out what's causing the problem. Consider a scenario where your computer suddenly c...