DigitalSanjiv

Union in C Language

Union in C Language

Union in C Language (Memory Sharing Explained)

Union in C language is a special user-defined data type. It allows multiple variables to share the same memory location. This makes unions different from structures in an important way.

In structures, each member gets separate memory space. In unions, all members overlap and share one memory block. Only one value remains valid at any given time.

This concept is known as memory sharing in C programming.

What Is a Union?

A union in C language is similar to a structure syntactically.
However, the internal memory behaviour is completely different.

All members of a union occupy the same memory address.
Writing one member automatically overwrites the previous value.

In simple comparison:

  • Structure → Separate memory per member
  • Union → Shared memory among members

Because of this behaviour, unions are mainly used in low-level programming.

Syntax of Union in C

The syntax of a union looks very similar to a structure.
The only difference is the keyword used.

union Data {
    int i;
    float f;
    char name[20];
};

All members declared inside the union share the same memory. The compiler allocates space equal to the largest member size. This similarity in syntax often confuses beginners initially.

Memory Allocation and Layout of Union in C

Memory allocation is the most important concept here. Understanding this makes unions easy to grasp.

In structures:
Memory equals sum of all member sizes.

In unions:
Memory equals size of the largest member only.

Example:

union Example {
    int i;      // 4 bytes
    float f;    // 4 bytes
    char c;     // 1 byte
};

Total memory allocated = 4 bytes.

Even though three members exist, memory stays minimal.

Why This Happens

All members start at the same memory address.
Each assignment overwrites previously stored data completely.

This behaviour enables memory sharing in C programs.

Union vs Structure in C

This is a very common exam and interview topic.
Students are often asked to compare both clearly.

FeatureStructureUnion
Memory allocationSeparate per memberShared memory
Total sizeSum of membersLargest member only
Multiple valuesPossibleNot possible
Data safetyHigherLower
Use caseGeneral programsMemory optimization

Understanding this table removes most beginner confusion. Many learners search for the difference between union and structure in C because both look similar syntactically. However, their memory models are completely different. While structures allocate separate memory for each member, unions allow memory sharing, making them suitable for low-level and embedded programming scenarios.

Union Example in C

Let us look at a simple working example.
This helps clarify union behaviour quickly.

#include <stdio.h>
#include <string.h>
union Data {
    int i;
    float f;
    char str[20];
};
int main() {
    union Data data;
    data.i = 100;
    printf("Integer: %d\n", data.i);
    data.f = 5.5;
    printf("Float: %.2f\n", data.f);
    strcpy(data.str, "Union Demo");
    printf("String: %s\n", data.str);
    return 0;
}

What This Example Shows

Each assignment replaces the previous stored value. All members share the same memory location internally.

After storing the string:

  • Integer becomes invalid
  • Float becomes invalid

This demonstrates memory sharing clearly.

How Memory Sharing Works Internally

Let us visualize what happens internally. Assume the union starts at memory address 1000.

Step-by-step behaviour:

  1. Store integer → Memory stores integer bytes
  2. Store float → Same bytes overwritten
  3. Store string → Memory reused again

All members map to the same memory region always.

This overlapping layout defines union behaviour.

When and Why to Use Union in C Programming

Union in C language should be used carefully.
It is ideal only in specific scenarios.

  1. Memory-Constrained Systems

Used heavily in embedded and firmware development.

  • Microcontrollers
  • IoT devices
  • Low-memory hardware
  1. Variant Data Storage

When a variable holds different data types over time.

Example scenarios:

  • Sensor readings
  • Status flags
  • Error codes
  1. Hardware-Level Programming

Unions are common in system-level development.

Used in:

  • Device drivers
  • Register mapping
  • Kernel programming
  1. Binary Data Interpretation

Useful when interpreting raw binary memory differently.

Examples include:

  • File parsing
  • Network packets

When NOT to Use Unions

Avoid unions in general-purpose applications. They are not suitable for everyday programming tasks.

Do not use unions when:

  • Multiple values must exist simultaneously
  • Data safety is critical
  • Code readability is important
  • Beginners are still learning basics

In such cases, structures are safer.

Limitations of Union in C Language

Despite advantages, unions have important limitations.

  1. Single Active Member

Only one member can hold valid data at once.

  1. Data Overwriting Risk

New assignments destroy previously stored values.

  1. Debugging Complexity

Overlapping memory makes debugging slightly harder.

  1. Portability Issues

Memory alignment may differ across compilers. This matters in cross-platform development.

Real-World Applications

Unions are widely used in professional systems. However, they appear less in beginner programs.

Common applications include:

  • Embedded firmware development
  • Operating system internals
  • Compiler design structures
  • Network protocol handling

These areas require efficient memory management.

Common Mistakes Students Make

Beginners often misunderstand union behaviour.
Avoid these common errors.

  • Treating union like structure
  • Reading overwritten values
  • Ignoring memory overlap
  • Using unions unnecessarily

Understanding fundamentals prevents logical bugs later.

Conclusion

Union in C language demonstrates efficient memory sharing. It allows multiple variables to reuse the same memory space.

Although similar to structures in syntax, behaviour differs greatly. Unions are powerful but must be used carefully.

They are especially useful in embedded systems and low-level programming. Understanding unions strengthens your grasp of memory concepts in C.

If you want deeper mastery, learn unions alongside:

Together, these topics build strong programming fundamentals.

FAQs

What is a union in C language?

A union is a data type where all members share memory.

How is union different from structure?

Structures allocate separate memory. Unions share one memory block.

Can multiple union members hold values simultaneously?

No. Only the most recently assigned member remains valid.

Why are unions used in C?

They are mainly used for memory optimization and low-level programming.

Are unions important for exams?

Yes. Union vs structure is a frequently asked question. Mostly asked in BCA, MCA and Engineering Examinations.

More on Union in C Please click the Link

Leave a Comment

Your email address will not be published. Required fields are marked *