Initializing nested structures
What you'll learn: How to cleanly set initial values for structures that contain other structures using nested braces.
The "Box within a Box" approach
In C, a structure can hold another structure as one of its members. Think of it like a shipping kit: you have a large Order box, and inside it, there is a smaller Address box. When you want to initialize the whole thing at once, you follow the same "box within a box" logic using curly braces {}.
Just as you use a pair of braces to initialize a standard struct, you use an additional, nested set of braces for the internal struct member. This keeps the data organized and tells the compiler exactly which values belong to the "inner" object.
How it looks in code
Let’s look at a coordinate system. We have a Point (x, y), and a Circle that uses a Point to define its center.
#include <stdio.h>
struct Point {
int x;
int y;
};
struct Circle {
struct Point center; // This is the nested structure
double radius;
};
int main() {
// Initializing the nested structure using inner braces
struct Circle myCircle = {
{10, 20}, // Initializes the 'center' (x = 10, y = 20)
5.5 // Initializes the 'radius'
};
printf("Center: (%d, %d)\n", myCircle.center.x, myCircle.center.y);
printf("Radius: %.1f\n", myCircle.radius);
return 0;
}
Why the extra braces matter
You might wonder if you can just list all the numbers in one long row, like {10, 20, 5.5}. While C technically allows this in some cases (called "brace elision"), it is dangerous. Using the nested braces makes your intent clear. If your Point struct grows later to include a z coordinate, the nested braces ensure your radius doesn't accidentally get assigned to the wrong field.
If you want to be even more precise, you can use designated initializers. This allows you to name the members explicitly, even inside the nesting:
struct Circle c = {.center = {.x = 10, .y = 20}, .radius = 5.5};
This "explicit is better than implicit" approach prevents bugs and makes your code much easier for others to read.
Key takeaway
To initialize a nested structure, use a nested set of curly braces that matches the hierarchy of your data.