How do I initialize structs in C?

The initialization of structs can be quite error-prone if the elements are initialized without their identifier. The following example illustrates an initialization.

Here’s an example of how you might define the mystruct structure.

Definition

#include <stdbool.h>

struct mystruct {
    int age;
    char name[50];
    bool flag;
};

Example 1

mystruct medarbetare2 = {21, "Anders", false};

The problem with this initialization method is that if you change the order of the struct elements in your definition, you must also modify the initialization order. A more robust approach is to initialize the elements with the name of the struct member without taking the order of the struct elements into account.

Example 2

mystruct medarbetare1 = {.flag = true, .age = 45, .name = "Joe"};