Course contentsShow
← C
Lesson 603 of 1,2199. Structures and UnionsFree lesson

Designated initializers in C99

Designated initializers in C99

What you'll learn: How to initialize specific members of a structure by name rather than relying on their order in memory.

The Problem with Order

In older versions of C, if you wanted to initialize a structure, you had to list the values in the exact same order they were defined in the struct. Imagine a structure representing a user profile with ten different fields. If you only wanted to set the age, but age was the eighth item in the list, you would be forced to provide dummy values for the first seven items just to reach it.

This "positional initialization" is brittle. If a teammate later rearranges the order of variables in the struct definition, your initialization code might silently break or assign the wrong data to the wrong variables.

Direct Targeting

C99 introduced designated initializers, which allow you to pick and choose which members to set using a period followed by the member name (the . operator). Think of it like a form where you only fill out the specific boxes that matter to you, leaving the rest to their default state.

When you use this method, any field you don't explicitly mention is automatically initialized to zero (or NULL for pointers).

How it looks in code

Here is how you can target specific members regardless of their position:

#include <stdio.h>

struct Smartphone {
    char *brand;
    int storageGB;
    float screenRes;
    int batteryHealth;
};

int main() {
    // We only care about brand and battery. 
    // We don't need to provide storageGB or screenRes!
    struct Smartphone myPhone = {
        .brand = "Pear",
        .batteryHealth = 95
    };

    printf("Brand: %s\n", myPhone.brand);
    printf("Battery: %d%%\n", myPhone.batteryHealth);
    
    // storageGB was skipped, so it defaults to 0
    printf("Storage: %dGB\n", myPhone.storageGB);

    return 0;
}

Why this is better

  1. Readability: Anyone reading your code knows exactly what value belongs to which variable without having to jump back and forth to the struct definition.
  2. Flexibility: You can list the members in any order you like inside the curly braces.
  3. Safety: If you add a new field to the middle of your struct later, your existing designated initializers won't break.

Key takeaway

Designated initializers use the .member = value syntax to make structure initialization more readable, flexible, and resistant to changes in the struct's definition.