Accessing and Initializing C Unions- Free C Programming Course

🚀 Learn BLE on Linux (BlueZ) – Programming Part 1

Hands-on Bluetooth Low Energy course. Special price: ₹399

Enroll Now on Udemy →
💬 Need help or career guidance? Ask us!Contact Us →

PREV_LEC | NEXT_LEC

Accessing and Initializing C Unions

Dot, arrow, designated initializers and a register byte-view, all compiled and verified

Declaring a type is only half the job; the other half is accessing and initializing C unions correctly. This lecture of our free C tutorial shows how to read and write union members with the dot and arrow operators, what really happens when you overwrite one member with another, and which initialization rules a C union follows. Everything is demonstrated with short programs you can compile, and we finish with a byte-view of a 32-bit register, the most common union trick in embedded C programming.

What You Will Learn

  • Accessing union members with . and ->
  • What a write to one member does to the others
  • Initializing a C union: first member, designated initializers, static storage
  • Reading a different member than you wrote (type punning) and its limits
  • A 32-bit register viewed as four bytes, with real output

Prerequisites

The previous lecture on defining a C union and its memory layout, plus pointer basics. A little knowledge of hexadecimal helps for the register example.

Accessing and Initializing C Unions: Member Access

Member access uses exactly the same operators as for a structure. With a union variable use the dot operator. With a pointer to a union use the arrow operator, which is shorthand for dereferencing the pointer and then using the dot.

You haveWriteMeaning
A union variable rr.rawMember raw of r
A pointer p to a unionp->rawSame as (*p).raw

Passing a pointer to a union into a function works just like passing a pointer to a structure, and avoids copying the whole union.

Overwriting Members: What Accessing C Unions Really Does

Accessing and initializing C unions safely starts with one fact: because the members share storage, every write replaces some or all of the bytes of every other member. The next program writes an integer, then a character, then a float, printing each value right after it is written. At the end it looks at the integer member again to show the damage.

#include <stdio.h>

union reading {
    int   raw;
    char  code;
    float volts;
};

int main(void)
{
    union reading r;

    r.raw = 90;
    printf("raw   = %d\n", r.raw);

    r.code = 'A';
    printf("code  = %c\n", r.code);

    r.volts = 3.3f;
    printf("volts = %.2f\n", r.volts);

    /* raw was overwritten by the float's bit pattern */
    printf("raw now holds 0x%08X\n", (unsigned)r.raw);

    union reading first = { 78 };   /* initialises first member only */
    union reading *p = &first;
    printf("init raw = %d, via pointer = %d\n", first.raw, p->raw);
    return 0;
}

Build and run

gcc -Wall -Wextra -o un1 un1.c
./un1

Expected output on a typical little-endian PC:

raw   = 90
code  = A
volts = 3.30
raw now holds 0x40533333
init raw = 78, via pointer = 78

Each line is correct only because the program read the same member it had just written. After the float 3.3 was stored, the integer member shows 0x40533333, the IEEE 754 bit pattern of 3.3, not the number 90 any more. Treat the other members as scrambled whenever you write one.

Timeline of one 4-byte union
Step 1raw = 90all 4 bytes carry the integer
Step 2code = Alowest byte replaced; upper bytes unchanged
Step 3volts = 3.3all 4 bytes replaced by the float pattern
Step 4read rawnot 90: raw bit pattern of 3.3

Initializing a C Union: Rules for Accessing and Initializing C Unions

A structure can take a value for every member in a brace list. A union cannot: only one member can hold a value, so only one initializer is allowed.

FormExampleWhich member is set
Plain bracesunion v a = { 7 };The first member declared
Designated (C99)union v b = { .f = 2.5f };The member you name
Static or global, no initializerstatic union v z;First member zeroed, padding zeroed
Local, no initializerunion v c;Indeterminate, do not read
Two valuesunion v d = { 1, 2 };Invalid, excess initializer

When you are accessing and initializing C unions, the type of the initializer for plain braces must suit the first member, so declaration order matters. Designated initializers remove that restriction and make the intent obvious to the reader:

#include <stdio.h>
#include <stdint.h>

union v { int32_t i; float f; };
static union v zeroed;            /* static storage: starts zeroed */

int main(void)
{
    union v a = { 7 };            /* braces fill the FIRST member  */
    union v b = { .f = 2.5f };    /* C99 designator picks any one  */
    union v *pb = &b;

    printf("a.i = %d\n", (int)a.i);
    printf("b.f = %.1f (via pointer: %.1f)\n", b.f, pb->f);
    printf("zeroed.i = %d\n", (int)zeroed.i);
    return 0;
}
gcc -Wall -Wextra -o desi desi.c
./desi

Expected output:

a.i = 7
b.f = 2.5 (via pointer: 2.5)
zeroed.i = 0

Reading a Different Member: Type Punning

Writing one member and reading another is called type punning. In C it is allowed: the stored bytes are reinterpreted as the type of the member you read. Three cautions apply. The result is a bit pattern, not a numeric conversion, so a float read as an integer is not the rounded value. The layout depends on byte order. And C++ forbids the same read, so shared headers can bite you later. For code that has to be portable everywhere, copy bytes with memcpy() instead.

Practical Example: A 32-Bit Register as Bytes

Peripheral registers are often 32 bits wide, but a bus protocol or a debug log may need single bytes. A union lets you present both views of one object:

#include <stdio.h>
#include <stdint.h>

union reg32 {
    uint32_t word;
    uint8_t  byte[4];
};

int main(void)
{
    union reg32 r;
    r.word = 0xA1B2C3D4u;

    for (int i = 0; i < 4; i++)
        printf("byte[%d] = 0x%02X\n", i, r.byte[i]);

    printf("this CPU is %s-endian\n", r.byte[0] == 0xD4 ? "little" : "big");
    return 0;
}
gcc -Wall -Wextra -o reg reg.c
./reg

Expected output on a little-endian machine:

byte[0] = 0xD4
byte[1] = 0xC3
byte[2] = 0xB2
byte[3] = 0xA1
this CPU is little-endian
0xA1B2C3D4 stored on a little-endian CPU
Indexbyte[0]byte[1]byte[2]byte[3]
Value0xD40xC30xB20xA1
Meaningleast significantmost significant

On a big-endian CPU the byte order would be reversed, which is why the program can also report the endianness of the machine it runs on. Never hard-code the order in firmware that may move to a different core.

Common Mistakes When Accessing and Initializing C Unions

  1. Reading before writing. A local union is uninitialized memory.
  2. Treating the other members as converted values. Reading raw after writing volts reinterprets bits.
  3. Using {1, 2} to fill two members. Only one initializer is accepted.
  4. Assuming byte order. The register program prints different bytes on a big-endian CPU.
  5. Parsing packets through a union. Padding and endianness make this non-portable; use shifts and masks.

Best Practices for Accessing and Initializing C Unions

  • Prefer designated initializers so a reader sees which member is set.
  • Always pair the union with a tag field that records the active member.
  • Use -Wall -Wextra; the compiler will flag excess initializers.
  • Keep punning for debugging and register views; use memcpy() for portable conversions.

Key Takeaways

  • Accessing and initializing C unions uses dot for a variable and arrow for a pointer, same as a struct.
  • A write changes the bytes every other member sees.
  • Brace initialization targets the first member; designators can target any one member.
  • Reading another member shows raw bits, and byte order matters.

Conclusion

Accessing and initializing C unions is straightforward as syntax, but the real skill is discipline: know which member is active, initialize on purpose, and treat cross-member reads as bit reinterpretation. With that habit the register-view trick above becomes a safe tool instead of a source of mystery bugs. Next, we compare the memory used by a structure and a union side by side, with offsets, padding and a RAM-saving calculation.

Frequently Asked Questions

How do you access union members in C?

Use the dot operator on a union variable (u.member) and the arrow operator on a pointer to a union (p->member). The syntax is identical to structures.

Can you initialize all members of a union in C?

No. A brace initializer without a designator sets only the first member. With C99 designated initializers you may choose a different single member, for example { .f = 2.5f }. Giving values for two members is an error or at best a warning.

What happens if I read a different member than I wrote?

The bytes are reinterpreted as the new type. In C this is permitted, but the result is not a numeric conversion, it is the raw bit pattern, and it may depend on byte order. In C++ the same read is undefined behavior.

What value does a global or static union start with?

A static or global union without an initializer starts zeroed: its first named member is zero-initialized and padding bits are zero. A local (automatic) union without an initializer holds indeterminate data.

Is using a union to check endianness correct?

It works on common compilers and is allowed in C, because reading another member reinterprets the stored bytes. For code that must be portable to C++ or strict compilers, use memcpy into a byte array instead.

Should I use a union to parse network or bus packets?

Avoid it. Struct padding and byte order vary between compilers and CPUs. Read bytes explicitly and assemble fields with shifts and masks.

Free Embedded C Course: Keep Going

In the next lecture we measure structure vs union memory with sizeof and offsetof, and see why padding can eat the savings.

PREV_LEC | NEXT_LEC

💬 Need help or career guidance? Ask us!Contact Us →

2 Comments

Leave a Reply

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

×

🚀 BLE on Linux (BlueZ)

Hands-on course. Only ₹399

Enroll Now →