In C, there are several ways to initialize structures:
struct Point { int x, y; }; struct Point p = {10, 20};
Fields are initialized in the declared order.
struct Point p = {.y = 20, .x = 10};
Fields can be initialized in any order.
struct Rect { int x, y, w, h; } r = {1, 2}; // w and h == 0
struct Color { int r, g, b; }; struct Pixel { struct Point pos; struct Color col; }; struct Pixel px = {{10,20}, {255,0,0}};
Named initialization will help avoid mistakes:
struct Pixel px = {.col = {.r = 255, .g = 0, .b = 0}};
Pitfalls:
Question: What happens if not all fields are explicitly specified during the initialization of a structure, and the structure is declared as an automatic local variable?
Expected wrong answer: "The remaining fields will always be equal to zero."
Correct answer: Automatic (local) variables that are not explicitly initialized retain uninitialized values. Partial initialization initializes only the explicitly stated fields, while others have undefined values (except for initialization using = {...}, where others will be zero only for static/global structures).
Example:
void foo() { struct Point { int x, y, z; } p = {1}; // p.x == 1, p.y and p.z == 0 (Only through = {1};) }
Story
In a graphical engine project, a field was added to the beginning of the vertex structure without reviewing the overall initialization method of objects in different modules. As a result, half of the modules began to incorrectly initialize color or coordinates, manifesting as rendering artifacts.
Story
In a video handler, a structure with nested pointers was partially initialized = {0}, which is correct for global variables, but not for locals. As a result, pointers contained "garbage," leading to operations with invalid addresses and hard-to-trace crashes.
Story
When adding new fields to a large structure, the authors did not update the old code sections with positional initialization. Due to mismatched field order and initializers, critical variables started to receive incorrect values. Only an audit of the structure and the implementation of named initialization helped to find the cause.