Structure initialization

16, Apr, 2019

Let say we have structure in C:

struct A {
    int x;
    int y;
};

You may initialize it three ways:

struct A a;
a.x = ...
a.y = ...

or

struct A a = { ..., ... };

or

struct A a = { .x = ..., .y = ... };

You may say what the difference?! But, there may be huge. Let say you implemented it, and then after years, after dozens of uses, someone modifies the A:

struct A {
    int x;
    int z;
    int y;
};

The last pattern saves the day…

p.s. What interesting C++ does not yet have it! It will in 2020. Ugh… But, even more - in current C++20 proposition, even when using designated initializers, these initializers must appear in order. With C++ - no save of the day, only the a doomsday. What a wonderful language!