Union in C

Union in C is a user-defined data type that lets multiple members share the same memory location. This makes it different from a structure. In a structure, each member gets its own storage. In a union, all members overlap in the same block of memory, and the size of the union is based mainly on its largest member.

This topic is important because unions help you understand memory sharing, low-level data representation, and efficient storage use in C. They are useful in embedded systems, protocol handling, hardware-level work, and situations where one memory block may need to be viewed in more than one way. In this article, we will understand what union in C is, how unions are declared, how memory is shared, how union members behave, the difference between union and structure, common use cases, and the mistakes beginners should avoid.

What is Union in C?

A union in C is a user-defined data type in which all members share the same memory location. Because the memory is shared, only one member’s value should be considered valid at a time in normal use.

For example, a union may contain an int, a float, and a char array, but all of them use the same memory space. If you store a value in one member and then store a value in another member, the old member’s stored bytes are overwritten.

A union stores different members in the same memory area, not in separate areas.

Why Union is Important in C

  • It helps save memory when only one of several values is needed at a time.
  • It teaches how memory can be reused for different views of data.
  • It is useful in embedded systems and low-level programming.
  • It helps in handling packed data, registers, and protocol data.
  • It makes the difference between independent storage and shared storage very clear.

Even when unions are not used daily by every beginner, understanding them improves your knowledge of how C lays out memory.

Syntax of Union in C

The syntax of union in C is similar to structure syntax. The difference is in how memory is allocated.

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

After defining the union, you can declare variables of that union type.

union Data value;

This creates one union variable named value.

How Memory Works in a Union

The most important thing to understand is that all union members start at the same memory location. They overlap each other.

If a union contains members of different sizes, the union must be large enough to hold its largest member.

MemberExample Size (bytes)
int i4
float f4
char name[20]20

In this case, the union size will usually be at least 20 bytes, because that is the largest member size.

The exact total size may also depend on alignment rules of the compiler, but the key beginner rule is simple: a union is sized mainly by its largest member.

Example of Union in C

Look at this simple example:

#include <stdio.h>

union Data {
    int i;
    float f;
};

int main(void)
{
    union Data value;

    value.i = 25;
    printf("value.i = %d\n", value.i);

    value.f = 3.14f;
    printf("value.f = %.2f\n", value.f);

    return 0;
}

When value.i is assigned, the shared memory stores the integer representation. When value.f is assigned later, the same memory is reused for the floating-point representation.

That means after writing to value.f, you should no longer expect value.i to still hold its previous meaningful integer value.

Union Members Overwrite Each Other

Because all members share the same memory, writing to one member changes the bytes used by the others.

OperationEffect
Store value in first memberShared memory gets that data
Store value in second memberSame memory is reused and old bytes are replaced
Read old member after overwriteResult is no longer logically reliable

This is the core behavior that makes unions different from structures.

Union vs Structure in C

Beginners often confuse union and structure because their syntax looks similar. Their memory model is very different.

FeatureUnionStructure
Memory allocationAll members share the same memoryEach member has separate memory
SizeUsually based on largest memberIncludes space for all members
Valid member useUsually one meaningful member at a timeAll members can hold values together
Main purposeMemory sharing / alternate viewsGrouping related data

If you need all members to hold data at the same time, use a structure. If you need one memory area to represent different kinds of data at different times, a union may be useful.

Common Uses of Union in C

  • Embedded systems and hardware register views
  • Protocol and packet interpretation
  • Memory-saving designs when only one member is active at a time
  • Type reinterpretation in controlled low-level code
  • Tagged data models when combined with an enum that tells which member is valid

A common practical pattern is to combine an enum and a union. The enum tells you what kind of data is currently stored, and the union holds the actual value.

enum DataType {
    INT_TYPE,
    FLOAT_TYPE
};

union Number {
    int i;
    float f;
};

This pattern becomes much safer when the program tracks which union member is currently valid.

Common Mistakes with Union in C

  • Thinking all union members can safely hold separate values at the same time
  • Forgetting that writing to one member overwrites the shared memory
  • Confusing union size with the sum of all member sizes
  • Using union when a structure is the correct tool
  • Reading a different member without understanding what bytes are actually stored
MistakeWhy it is wrongCorrect understanding
Assuming i and f both remain valid togetherThey use the same storageNormally only one active interpretation should be trusted
Adding all member sizes to estimate union sizeUnion members overlapUnion size is mainly based on the largest member
Using union for ordinary grouped recordsWrong memory modelUse structure when members must coexist

The best beginner rule is simple: a union is for shared memory, not for storing many independent values together.

Best Practices for Union in C

  • Use union only when shared memory is really intended.
  • Document which member is expected to be valid at a given time.
  • Combine union with an enum when you need to track the active member type.
  • Use structure instead when all members must exist together.
  • Be careful when using unions in low-level or compiler-dependent contexts.

Good union usage is deliberate. If the memory-sharing purpose is not clear, the code becomes harder to reason about.

FAQs

What is union in C?

Union in C is a user-defined type in which all members share the same memory location.

What is the difference between union and structure in C?

In a union, all members share the same memory. In a structure, each member has separate storage.

How is the size of a union determined in C?

The size of a union is usually based on its largest member, with possible extra alignment depending on the compiler.

Can all union members store values at the same time in C?

They share the same memory, so storing a value in one member affects the bytes seen by the others. In normal use, only one member should be treated as valid at a time.

Where is union used in C?

Unions are used in embedded systems, memory-efficient designs, protocol handling, low-level programming, and cases where data needs multiple interpretations through shared storage.