🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →C Union Explained for Embedded
One block of memory, many types: the C union for firmware developers
A C union is a data type that lets several members of different types share one block of memory. If you are following this free C programming course for embedded systems, the union is the first time you will meet a type where writing one field deliberately destroys another, and that is exactly why it is so useful on a microcontroller with only a few kilobytes of RAM. This lecture explains how a C union is declared, how it sits in memory, how big it is, and where embedded C programming uses it every day.
What You Will Learn
- What a C union is and how it differs from a structure
- Three ways to define and declare union variables
- How the members overlap in memory, shown as a diagram
- How the compiler decides the size of a union
- Real embedded use cases: protocol payloads, register views, float bit inspection
- The mistakes that make union code unsafe
Prerequisites
Basic structures (definition, member access with the dot operator), the sizeof operator, and the fixed-width types from <stdint.h>. We use uint8_t, uint16_t and uint32_t because embedded code needs types whose size you can rely on.
What Is a C Union?
A union looks like a structure and is accessed like a structure, but the keyword is union and the memory rule is completely different. A structure is like a row of lockers: each member owns its own. A union is a single locker with several labels stuck on the door: whichever label you use, you open the same locker.
This gives you one clear benefit and one clear responsibility. The benefit is saved memory: when only one of several alternatives is needed at any moment, you pay for the largest alternative instead of the sum of all of them. The responsibility is bookkeeping: the language will not tell you which member currently holds valid data, so your program must remember.
Union Syntax in C
There are three common styles. They all define the same kind of type; the difference is only how you name it and when you create variables.
| Style | Example | When to use |
|---|---|---|
| Tag, declare later | union payload { ... }; then union payload p; | Most readable; the default choice |
| Define and declare together | union spare { ... } inline_var; | One-off variable, no reuse |
| typedef | typedef union { ... } fbits_t; | When you want to write fbits_t x; without the keyword |
The following program uses all three styles and prints the size of each union. The member names are chosen to look like firmware data: a command byte, a temperature in deci-degrees, and a tick counter.
#include <stdio.h>
#include <stdint.h>
union payload {
uint8_t cmd;
uint16_t temp_dc;
uint32_t ticks;
};
union spare { uint8_t a; uint16_t b; } inline_var;
typedef union { float f; uint32_t bits; } fbits_t;
int main(void)
{
union payload p;
p.ticks = 100000;
printf("ticks = %u\n", (unsigned)p.ticks);
printf("sizeof(union payload) = %zu\n", sizeof p);
printf("sizeof(inline_var) = %zu\n", sizeof inline_var);
fbits_t x = { .f = 1.0f };
printf("1.0f bits = 0x%08X\n", (unsigned)x.bits);
return 0;
}
Build and run
gcc -std=c11 -Wall -Wextra -o msg msg.c
./msg
Expected output:
ticks = 100000
sizeof(union payload) = 4
sizeof(inline_var) = 2
1.0f bits = 0x3F800000
Notice that union payload holds three members of 1, 2 and 4 bytes yet occupies just 4 bytes, the size of the biggest. The last line shows a classic trick: store a float through one member and read its raw 32-bit pattern through another. The value 0x3F800000 is how IEEE 754 stores 1.0.
How a C Union Shares Memory
Every member of a union starts at offset zero. They differ only in how many bytes of that shared block they use. The diagram shows the 4-byte union payload from the program above.
Write ticks and you have changed what cmd and temp_dc would read. Write cmd and you have changed the lowest byte of ticks on a little-endian CPU, while the upper bytes keep whatever was there before. That second effect is why you must never assume the other members are zero.
Size of a C Union
The rule has two parts. First, the union must be big enough for its largest member. Second, the total is rounded up so that arrays of the union stay correctly aligned for the member with the strictest alignment. In practice:
sizeof(union)is at least the size of the largest member.- If a member is an array like
char buf[5]and another member needs 4-byte alignment, the union grows to 8 bytes. - Always print
sizeofon your target compiler; do not do the arithmetic in your head.
Why Embedded C Programming Uses Unions
| Use case | What the union does | Example |
|---|---|---|
| Protocol messages | One buffer holds whichever message variant arrived | Command, status and data frames sharing a payload area |
| Hardware register views | See one 32-bit register as a word or as four bytes | Reading a status register byte by byte |
| Float inspection | Look at the raw bits of a float | Debugging sensor math, sending floats over a bus |
| RAM saving | Alternatives share storage | Event queues with several event shapes |
| Variant data | A value that can be int, float or text | Small interpreters, configuration parsers |
Common Mistakes With a C Union
- Using two members at once. They overlap. Write one, read the same one.
- Assuming the other members are zero. A union does not clear itself when you assign a member.
- Forgetting a tag. Without a field that says which member is active, a receiver cannot interpret the data safely.
- Assuming a fixed byte order or layout. Overlapping bytes depends on endianness and padding, so do not use a union as a wire format.
- Comparing whole unions with
==. C does not allow it; compare the active member.
Warning
A union gives you power over memory but no safety net. A wrong member read compiles without a single warning and produces plausible-looking garbage.
Best Practices and Security Considerations
- Wrap the union and its tag in one struct, so the two always travel together.
- Use fixed-width integer types so the sizes are the same on every compiler you target.
- Treat data arriving from a network or a bus as untrusted: check the tag against the known range before touching the payload.
- Zero the whole union before reuse if parts of it may later be sent out, to avoid leaking stale bytes.
- Document which member is active in each state of your program.
Key Takeaways
- A C union stores all members at the same address; its size is that of the largest member plus alignment.
- Only one member is meaningful at a time, and the programmer must track which.
- Unions save RAM, give register views and let you inspect raw bits.
- Syntax mirrors a structure; only the keyword and the memory rule change.
Conclusion
The C union is a small feature with a big effect on embedded C programming: one declaration lets a buffer take several shapes, which is why you will find it in drivers, protocol stacks and bootloaders. You now know the syntax, the memory model and the traps. Next we practise the mechanics: accessing members with the dot and arrow operators, and the rules for initialising a union.
Frequently Asked Questions
What is a union in C?
A union is a user-defined type whose members all share the same memory. The compiler reserves enough space for the largest member, and writing one member overwrites the others. Only one member holds a meaningful value at a time.
What is the difference between a struct and a union in C?
In a struct every member gets its own storage and all of them hold values at once. In a union all members start at the same address and overlap, so the union is as large as its biggest member (plus any alignment padding).
How is the size of a C union calculated?
It is the size of the largest member, rounded up so the union is correctly aligned for its most strictly aligned member. Use sizeof instead of guessing, for example a union holding char buf[5] and a 32-bit integer is 8 bytes, not 5.
Why are unions popular in embedded C programming?
RAM is scarce, and firmware often handles messages or register values that come in several shapes. A union lets one buffer represent any of them, and also gives byte-level or bit-level views of a hardware register.
Can I use two union members at the same time?
No. After you write one member, the other members do not hold their own independent values. Keep track of which member is active, usually with a separate tag field.
Is a union the same as an enum?
No. An enum is a set of named integer constants. A union is a storage-sharing aggregate type. They are often combined: an enum value acts as the tag that says which union member is active.
Keep Learning C for Free
The next lecture covers accessing and initializing unions, including designated initializers and a byte-view of a 32-bit register. Part of our free embedded C course.

1 Comment