Initializing a union
What you'll learn: How to properly set the starting value of a union while respecting its "one-member-at-a-time" rule.
Because a union stores all its members in the same physical memory location, initializing one is a bit different than initializing a struct. You cannot set every member at once because they all overlap. If you try to give every member a value, you'll just end up overwriting the same spot in memory over and over.
The First Member Rule
In C, when you initialize a union using curly braces { }, the compiler defaults to the first member defined in the union template.
Imagine a single parking spot that can hold either a motorcycle or a compact car. If you "initialize" that spot with a motorcycle, the car can't be there at the same time. In your code, the compiler looks at your list of members and says, "Unless told otherwise, I will assume the value you provide belongs to the first item on this list."
Designated Initializers
If you want to initialize a member that isn't the first one, you must use designated initializers. This uses the dot notation (.member_name = value) inside the curly braces. This tells the compiler exactly which "version" of the data you are providing.
#include <stdio.h>
union Data packet {
int id; // Member 1
float weight; // Member 2
char code; // Member 3
};
int main() {
// 1. Default initialization (sets the first member: id)
union Data d1 = { 101 };
// 2. Designated initialization (sets a specific member: weight)
union Data d2 = { .weight = 75.5f };
// 3. One-at-a-time assignment (not initialization, but common)
union Data d3;
d3.code = 'A';
return 0;
}
Important Limitations
You cannot initialize multiple members at the same time. For example, union Data d = { 101, 75.5f }; will cause a compiler error or warning. Even though the union has space for different types, it only has space for one value at any given moment.
Think of it like a light switch: it can be "On" or "Off," but you can't initialize it to be both simultaneously. You pick one state to start with, and the memory is carved out to fit the largest possible member.
Key takeaway
By default, a union initialization targets the first member, but you can target any specific member using the .member_name syntax.