Skip to main content

Unions in C: Shared Memory for Different Types 🤝

Mentor's Note: Think of a structure as an apartment with separate rooms for everyone (each member has their own memory). A union, on the other hand, is like a single rental locker. You can store a bicycle, a guitar, or a suitcase inside, but only one at a time. The locker size is matched to the largest item. If you put a guitar in, whatever was in there before is cleared out! 💡

📚 Educational Content: In board exams (GSEB / CBSE) and university computer science exams, "Structure vs Union" is one of the most frequently asked comparison questions. Scoring high requires writing down the definitions, illustrating their memory layouts, and explaining their respective sizeof calculations clearly.

:::info What You'll Learn By the end of this tutorial, you'll know:

  • The difference between a union and a structure in terms of memory.
  • How to define, declare, and initialize unions in C.
  • How C calculates the sizeof a union based on its largest member.
  • When to use unions (memory constraints vs type punning).
  • A real-world example representing colors (individual RGB components vs a single 32-bit integer). :::

🌟 The Scenario: The Hybrid Data Packet

Imagine you are writing software for a low-power temperature sensor that sends reports over a radio transmitter:

  • The sensor sends either a temperature reading (as a float), a status code (as an int), or an error flag (as a char).
  • It never sends all three at the same time.

If you group them in a structure:

  • struct Report { float temp; int status; char err; };
  • Memory used: $4 + 4 + 1 = 9$ bytes (plus alignment padding = 12 bytes).
  • The Logic: Since we only send one of these values at a time, keeping separate memory slots for all three is wasteful. ❌
  • The Result: By using a union, we allocate a single 4-byte slot. It handles all three types, saving critical space on our embedded transmitter. ✅

📖 Concept Explanation

A union is a user-defined data type in C similar to a structure. However, while a structure allocates distinct memory locations for each of its members, a union allocates only one shared memory block for all its members.

1. Syntax of Unions

The syntax for defining and declaring a union is almost identical to a structure, using the keyword union:

union Measurement {
int integer_val;
float float_val;
char char_val;
};

So what? When you declare a variable union Measurement m;, the compiler allocates a single block of memory. The size of this block is equal to the size of the largest member (in this case, 4 bytes for the int or float).

2. Shared Memory Behavior

Because all members share the same memory location, writing to one member overwrites the others.

union Measurement m;
m.integer_val = 100;
m.float_val = 3.14f; // This overwrites integer_val!

So what? If you attempt to print m.integer_val after assigning to m.float_val, you will get corrupted gibberish because the binary representation of 3.14 is now occupying that shared space.

3. Comparison: Struct vs Union

FeatureStructure (struct)Union (union)
MemoryEach member gets a unique memory address.All members share the same memory address.
SizeSum of sizes of all members (+ padding).Size of the largest member.
AccessYou can access all members simultaneously.Only one member can be accessed reliably at a time.
Use CaseGrouping unrelated values that exist together.Saving memory, or viewing the same bits differently.

4. Type Punning

Unions are commonly used for "Type Punning" — the practice of writing a value as one data type and reading it as another. For example, looking at the individual bytes of a float, or mapping RGB colors to a single integer.


🧠 Step-by-Step Logic

Let's write a program to demonstrate how unions share memory and how they can be used for color representation (combining four 8-bit bytes into one 32-bit integer).

  1. Start 🏁
  2. Define a union containing:
    • A structure of 4 bytes representing red, green, blue, and alpha channels.
    • A single 32-bit integer representing the combined color value.
  3. Declare a color union variable.
  4. Set the individual RGBA channels.
  5. Print the merged 32-bit hex value.
  6. End 🏁

💻 C Implementation (C99)

#include <stdio.h>

// Struct representing 4 bytes of an RGBA color
struct ColorChannels {
unsigned char r;
unsigned char g;
unsigned char b;
unsigned char a;
};

// Union sharing memory between the channels and a 32-bit integer
union Pixel {
struct ColorChannels rgba; // 4 bytes
unsigned int raw_value; // 4 bytes
};

int main() {
// 🛒 Scenario: Color Graphics Buffer
// 🚀 Action: Set individual colors and retrieve the combined pixel value

union Pixel pixel;

// 1. Calculate and print sizes
printf("Size of struct ColorChannels: %lu bytes\n", sizeof(struct ColorChannels));
printf("Size of union Pixel : %lu bytes\n\n", sizeof(union Pixel));

// 2. Set individual channels
pixel.rgba.r = 255; // Full Red
pixel.rgba.g = 128; // Half Green
pixel.rgba.b = 0; // No Blue
pixel.rgba.a = 255; // Fully Opaque

// 3. Read the shared 32-bit memory as a single raw integer (Type Punning)
printf("--- Reading Shared Memory ---\n");
printf("Red Channel : %u\n", pixel.rgba.r);
printf("Green Channel: %u\n", pixel.rgba.g);
printf("Hex Raw Value: 0x%08X\n", pixel.raw_value);

// 4. Overwrite using the raw value
pixel.raw_value = 0xFF00FF00; // Opaque Green in RGBA format (depending on system endianness)
printf("\n--- After Overwriting raw_value with 0xFF00FF00 ---\n");
printf("Red Channel : %u\n", pixel.rgba.r);
printf("Green Channel: %u\n", pixel.rgba.g);
printf("Alpha Channel: %u\n", pixel.rgba.a);

return 0;
}

// Output:
// Size of struct ColorChannels: 4 bytes
// Size of union Pixel : 4 bytes
//
// --- Reading Shared Memory ---
// Red Channel : 255
// Green Channel: 128
// Hex Raw Value: 0xFF8000FF
//
// --- After Overwriting raw_value with 0xFF00FF00 ---
// Red Channel : 0
// Green Channel: 255
// Alpha Channel: 255

Note: Hex output value might vary depending on whether your computer architecture is Little Endian or Big Endian.


📊 Sample Dry Run

Let's trace the shared memory changes of the pixel union variable:

StepOperationpixel.rgba.rpixel.rgba.gpixel.raw_value (Hex)Description
1Init RGBA2551280xFF8000FFShared memory contains bytes of R, G, B, A
2Read Raw2551280xFF8000FFValue read as combined 32-bit int ⚙️
3Write Raw02550xFF00FF00Overwriting raw integer resets components

📉 Complexity Analysis

Time Complexity ⏱️

  • Read/Write Operations: $O(1)$ - Direct memory reading and writing.

Space Complexity 💾

  • Space Saved: Up to $(N - 1) \times S$ bytes compared to structures, where $N$ is the number of members and $S$ is their average size.
  • Auxiliary Space: $O(1)$.

🎯 Practice Problems

Easy Level 🟢

  1. Define a union named Data that has an int, double, and char. Write a program to assign values to each member one by one, printing the value of the active member immediately after assignment.

Medium Level 🟡

  1. Write a program to check the "Endianness" of your computer system using a union. Create a union with an integer (0x0001) and a char array. If the first element of the char array is 1, the system is Little Endian; if it is 0, it is Big Endian.

Hard Level 🔴

  1. Create a structure Sensor that contains a type identifier (enum SENSOR_TYPE) and a union containing the actual sensor reading (either float temperature, int humidity, or char motion_detected status). Write a function to print the reading dynamically based on the sensor type (tagged union pattern).

❓ Frequently Asked Questions

Details

Q: What happens if I write to one member of a union and read from another? The memory will return the binary values interpreted as the second type. For example, if you write the float 1.0 and read it as an integer, you won't get 1, but rather 1065353216 (the binary representation of 1.0 in IEEE-754 format).

Details

Q: Can a union contain a structure, or a structure contain a union? Yes! This is highly common. In systems programming, we often embed structures inside unions (like our color example) or put unions inside structures to manage optional/variant data fields.

Details

Q: Why does the sizeof a union sometimes exceed the size of its largest member? Like structures, compilers apply memory alignment padding to unions to match the alignment requirements of their largest member. If a union contains a struct or array, it might be padded to match the platform's alignment word boundary.


📚 Best Practices & Common Mistakes

✅ Best Practices

  • Use Tagged Unions: Always pair a union with an indicator variable (like an enum/integer tag) inside a parent struct. This tells you which member is currently active, preventing reading corrupted data.
  • Document Endianness: If you use unions for type punning, document that byte order will change between Little Endian (x86/ARM) and Big Endian network protocols.

❌ Common Mistakes ⚠️

  • Simultaneous Access: Assigning value to member A, then value to member B, and subsequently expecting member A to still hold its original value.
  • Wrong Initialization: You can only initialize the first member of a union inside braces: union MyUnion u = {10}; assigns 10 to the first declared member.

✅ Summary

In this tutorial, you've learned:

  • ✅ Unions share a single memory location for all their member variables.
  • ✅ The size of a union is equal to the size of its largest member (plus alignment padding).
  • ✅ Writing to a union member overwrites all other members.
  • ✅ Unions are vital for memory savings in embedded systems and for type punning operations.
  • ✅ Structs hold all members simultaneously, whereas unions hold only one member at a time.

💡 Interview Tips & Board Focus 👔

  • Classic Interview Question: "What is the difference between struct and union?". Focus on memory sharing and the sizeof output. Write down a brief comparison table to earn full marks.
  • Memory Footprint Tracing: Be prepared to trace what happens when you modify a union byte-by-byte.

📚 Further Reading

Continue your learning path:


📍 Visit Us

🏫 VD Computer Tuition Surat

VD Computer Tuition
📍 Address
2/66 Faram Street, Rustompura
Surat395002, Gujarat, India
📞 Phone / WhatsApp
+91 84604 41384
🌐 Website

Computer Classes & Tuition — Areas We Serve in Surat

AdajanAlthanAmroliAthwaAthwalinesBhagalBhatarBhestanCanal RoadChowkCitylightDumasGaurav PathGhod Dod RoadHaziraJahangirpuraKamrejKapodraKatargamLimbayatMagdallaMajura GateMota VarachhaNanpuraNew CitylightOlpadPalPandesaraParle PointPiplodPunaRanderRing RoadRustampuraSachinSalabatpuraSarthanaSosyo CircleUdhnaVarachhaVed RoadVesuVIP Road
📞 Call Sir💬 WhatsApp Sir