What are Nested Structure Initialization Rules- Online Embedded C Programming Classes

🚀 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

Free C Programming Course · Chapter 10 · Lecture 12

Nested Structure Initialization Rules

Define inner structures first, reuse them, initialise multi-level data with braces, and learn which nesting the compiler rejects. A free C tutorial for embedded C programming.

Topics in This Free Embedded C Course Lecture

nested structure initialization in C designated initializers multi-level nesting incomplete type error free C tutorial embedded C programming

In the last lecture we declared the inner structure inside the outer one. That works, but most real code does it the other way round: it defines the inner type first and reuses it. This brings new questions. In what order must definitions appear? How does nested structure initialization in C work when braces sit inside braces? Which kinds of nesting are illegal? This lecture of our free C programming course answers each one with tested programs and the exact compiler messages you will see, which is the knowledge you need for C programming for embedded systems.

What You Will Learn

  • Why defining the inner structure outside is usually better
  • The order rule: inner definition before outer definition
  • Nested structure initialization in C with matching braces
  • C99 designated initializers for nested members
  • Three-level nesting and the chained access path
  • Why a structure cannot contain itself, and what to use instead

Prerequisites

Complete the previous lecture on nested structures in C first. You should know how to declare a structure variable and use chained dot access such as r1.taken.ss.

Nested Structure Initialization in C: Define the Inner Type First

When the inner structure is written inside the outer one, only that outer structure is naturally associated with it. If a second structure needs the same kind of member, you would have to repeat the definition. Defining the inner type separately, before the outer one, removes that problem. Any number of structures can then declare members of that type.

struct clock_time {
    int hh;
    int mm;
    int ss;
};

struct calendar_day {
    int day;
    int month;
    int year;
};

struct alarm_cfg {
    struct clock_time start;
    struct clock_time stop;
    int               enabled;
};

Here struct clock_time is reused twice inside alarm_cfg, as start and stop, and it can be reused in any other structure you write later. This reuse is the main reason firmware libraries define small building-block structures.

One inner type, many users

1

clock_time

Defined once, at file level, with hh, mm and ss.

2

alarm_cfg

Uses clock_time twice, for start and stop.

3

timestamp

Uses clock_time once, next to a calendar_day.

The Order Rule for Nested Structures

An outer structure that contains an inner structure by value needs to know the inner structure’s size, so the compiler must already have seen the complete inner definition. If you reverse the order, compilation stops. Try this file, n5_order_bad.c:

struct packet {
    int            id;
    struct header  hdr;      /* header is not defined yet */
};

struct header {
    int length;
    int flags;
};
$ gcc -std=c11 n5_order_bad.c -o n5
n5_order_bad.c:6:20: error: field 'hdr' has incomplete type
    6 |     struct header  hdr;      /* ERROR: struct header not defined yet */
      |                    ^~~

Rule: if the inner structure is defined outside, its definition must appear before the outer structure that contains it by value. The phrase “incomplete type” in an error message nearly always means the compiler has not yet seen the full definition.

Multi-Level Nested Structure Initialization in C

Nesting can continue through any number of levels. In the next program a log_entry contains a timestamp, which contains a calendar_day and a clock_time. That is three levels deep, so the deepest member needs three dots: e.when.time.ss.

LevelStructureExample access
1log_entrye.code
2timestamp (member when)e.when
3calendar_day / clock_time (members date, time)e.when.date.year, e.when.time.ss

Nested Structure Initialization in C With Braces

Nested structure initialization in C follows one simple idea: every structure level gets its own pair of braces, and values appear in the order the members were declared. Study the full program below, saved as n2_nested_outside.c.

#include <stdio.h>

struct clock_time   { int hh; int mm; int ss; };
struct calendar_day { int day; int month; int year; };

struct timestamp {
    struct calendar_day date;
    struct clock_time   time;
};

struct log_entry {
    int              code;
    struct timestamp when;
};

struct alarm_cfg {
    struct clock_time start;
    struct clock_time stop;
    int               enabled;
};

int main(void)
{
    struct log_entry e = { 404, { {30, 10, 2026}, {12, 29, 5} } };
    struct alarm_cfg a = { {6, 30, 0}, {22, 0, 0}, 1 };

    printf("code %d at %02d-%02d-%04d %02d:%02d:%02d\n",
           e.code,
           e.when.date.day, e.when.date.month, e.when.date.year,
           e.when.time.hh,  e.when.time.mm,    e.when.time.ss);

    printf("alarm %s from %02d:%02d to %02d:%02d\n",
           a.enabled ? "ON" : "OFF",
           a.start.hh, a.start.mm, a.stop.hh, a.stop.mm);

    printf("sizeof(struct log_entry)=%zu\n", sizeof(struct log_entry));
    return 0;
}
$ gcc -Wall -Wextra -std=c11 n2_nested_outside.c -o n2
$ ./n2
code 404 at 30-10-2026 12:29:05
alarm ON from 06:30 to 22:00
sizeof(struct log_entry)=28

Which braces fill which structure in log_entry e

Brace groupFillsValues
Outer pairstruct log_entry404, then the timestamp group
Second pairstruct timestamp (when)date group, then time group
Third pair, firststruct calendar_day (date)30, 10, 2026
Third pair, secondstruct clock_time (time)12, 29, 5

The compiler allows you to leave out inner braces and write all values in one flat list, but that is hard to read and easy to get wrong. With the inner braces, anyone can see which values belong to which structure. If you supply fewer values than there are members, the remaining members are set to zero.

Designated Initializers for Nested Structures

Since C99 you can name the members you want to set. This is clearer for configuration structures with many fields, and it keeps working if someone reorders the members. Everything you do not name becomes zero. Save this as n6_designated.c:

#include <stdio.h>

struct clock_time   { int hh, mm, ss; };
struct calendar_day { int day, month, year; };
struct timestamp {
    struct calendar_day date;
    struct clock_time   time;
};

int main(void)
{
    struct timestamp t = {
        .date = { .day = 30, .month = 10, .year = 2026 },
        .time.hh = 17,
        .time.mm = 45
    };

    printf("%02d-%02d-%04d %02d:%02d:%02d\n",
           t.date.day, t.date.month, t.date.year,
           t.time.hh, t.time.mm, t.time.ss);

    struct timestamp zero = {0};
    printf("zero: %d %d %d\n", zero.date.year, zero.time.hh, zero.time.ss);
    return 0;
}
$ gcc -Wall -Wextra -std=c11 n6_designated.c -o n6
$ ./n6
30-10-2026 17:45:00
zero: 0 0 0

Notice that ss was never named and printed as 00. Also notice that = {0} zeroes every member at every level, which is the safest way to start any nested structure.

A Structure Cannot Contain Itself

A structure must not contain a member of its own type. If it did, the size of the structure would have to include itself, which is infinite. The compiler refuses:

struct node_bad {
    int value;
    struct node_bad inner;   /* not allowed */
};
$ gcc -std=c11 n3_self_nest_bad.c -o n3
n3_self_nest_bad.c:5:21: error: field 'inner' has incomplete type
    5 |     struct node_bad inner;   /* ERROR: size would be infinite */
      |                     ^~~~~

A pointer to the same structure type is perfectly legal, because every pointer has a fixed size no matter what it points to. This is the basis of linked lists, which you will meet later:

struct node {
    int          value;
    struct node *next;
};

int main(void)
{
    struct node c = { 30, NULL };
    struct node b = { 20, &c };
    struct node a = { 10, &b };

    for (struct node *p = &a; p != NULL; p = p->next)
        printf("%d ", p->value);
    printf("\n");
    return 0;
}
10 20 30
sizeof(struct node)=16

The sizeof line comes from the full program, which also prints sizeof(struct node). On a 64-bit machine it is 16 bytes (4-byte value, 4 bytes of padding, 8-byte pointer); on a 32-bit microcontroller it is typically 8.

DeclarationLegal?Reason
Inner struct defined before outer, used by valueYesSize is known
Inner struct defined after outer, used by valueNoIncomplete type
Struct containing itself by valueNoInfinite size
Struct containing a pointer to itselfYesA pointer has a fixed size

Common Mistakes

  • Wrong definition order. The inner structure must come first.
  • Flat initializer lists. Without inner braces, a single misplaced value shifts every later member.
  • Mixing up the declared order. Positional initializers follow declaration order, not the order you would say the fields aloud.
  • Self-containing structures. Use a pointer member instead.

Best Practices for Nested Structure Initialization in C

Tips for embedded projects

  • Put shared inner structures in a header file so every source file sees the same definition.
  • Use designated initializers for configuration blocks with more than four fields.
  • Start with = {0} and then set only what matters.
  • Declare constant configuration as const; the compiler can place it in flash instead of RAM on many microcontroller toolchains.

Summary and Key Takeaways

  • Define an inner structure outside the outer one when it will be reused.
  • The inner definition must come before the outer structure that contains it by value.
  • Nested structure initialization in C uses one brace pair per level, in declaration order. Get that habit right and every configuration block you write becomes easier to read.
  • Designated initializers name the members and zero the rest.
  • A structure cannot contain itself, but it may contain a pointer to itself.

Conclusion

You can now build reusable, multi-level structures and fill them in correctly. This is a skill you will use whenever you write a configuration block for a peripheral or a frame for a protocol. Next we meet pointers to structures, which let functions work on a structure without copying it.

Suggested Images for This Lecture

Image ideaALT text
Three coloured boxes nested inside each otherMulti-level nested structure initialization in C with one brace pair per level
Compiler error screenshot for incomplete typeIncomplete type error when nested structure definition order is wrong in C
Arrows showing a node pointing to the next nodeStructure with a pointer to itself in a free C programming course

Frequently Asked Questions

How do I initialise a nested structure in C?

Use one pair of braces per structure level and list values in declaration order, or use designated initializers such as .time.hh = 17.

Must the inner structure be defined before the outer one?

Yes, when the outer structure contains it by value. Otherwise the compiler reports an incomplete type error.

Can I skip the inner braces?

The compiler accepts a flat list, but it is error-prone. Use inner braces for clarity.

What happens to members I do not initialise?

In an initializer list the remaining members are set to zero.

Why can a structure not contain itself?

Its size would be infinite. Use a pointer to the structure instead.

Do designated initializers work on embedded compilers?

Most modern embedded toolchains support C99, including GCC-based ones, but check your compiler’s language mode.

Continue the Free C Programming Course

Next up: pointers to structures, the arrow operator and why the parentheses in (*p).member matter.

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 →