Initialise Structs and Arrays Safely With Designated Initialisers in C
Use C99 designated initializers to set struct fields and array slots by name, zero the rest and avoid uninitialized reads. Includes flags and pitfalls.

An uninitialized variable is one of the quietest sources of undefined behavior in C. The compiler does not zero a local struct, nothing warns you when you forget a field, and the program reads whatever bytes were on the stack. Designated initializers, added in C99, fix the common version of the problem: you name the fields you care about, and the language guarantees that every other member is set to zero. This walkthrough shows how to write them for structs, arrays and nested aggregates, what the standard promises, and which compiler flags catch the mistakes that remain. It uses C17 with GCC 14 and Clang 19.
Step 1: the problem with positional initializers
A positional initializer lists values in declaration order. It works until someone adds or reorders a field.
#include <stdio.h>
struct server {
const char *host;
int port;
int timeout_s;
int retries;
};
int main(void) {
struct server s = { "example.org", 8080, 30 };
printf("%s:%d timeout=%d retries=%d\n", s.host, s.port, s.timeout_s, s.retries);
return 0;
}example.org:8080 timeout=30 retries=0The three values map to host, port and timeout_s by position, and retries is zero because an initializer list shorter than the aggregate zero-fills the rest (C11 6.7.9p21). That part is safe. The fragile part is the position: if a later commit inserts bool tls; before timeout_s, every positional initializer in the codebase silently assigns the old values to the wrong fields, and the compiler accepts it as long as the types convert.
Step 2: name the fields
A designated initializer names the member with a dot. The order does not matter, and omitted members are zero.
#include <stdio.h>
struct server {
const char *host;
int port;
int timeout_s;
int retries;
};
int main(void) {
struct server s = {
.host = "example.org",
.port = 8080,
.timeout_s = 30,
};
printf("%s:%d timeout=%d retries=%d\n", s.host, s.port, s.timeout_s, s.retries);
return 0;
}example.org:8080 timeout=30 retries=0The output is the same, but the intent is explicit, and inserting a new field cannot shift the others. The rule that omitted members are zero comes from the same paragraph of the standard: any subobject not explicitly initialized is initialized the same as an object with static storage duration, which means arithmetic types become zero and pointers become null. That is why struct server s = {0}; and struct server s = { .port = 80 }; are both safe, and why a bare struct server s; is not.
Step 3: arrays by index
Arrays accept [index] designators, and the array's length is taken from the highest index when you leave it out.
#include <stdio.h>
enum level { LOW, MID, HIGH, LEVEL_COUNT };
static const char *const names[] = {
[LOW] = "low",
[MID] = "mid",
[HIGH] = "high",
};
int main(void) {
int sparse[6] = { [2] = 5, [4] = 7 };
printf("names has %zu entries\n", sizeof names / sizeof names[0]);
for (int i = 0; i < 6; i++) printf("%d ", sparse[i]);
printf("\n");
printf("%s\n", names[MID]);
return 0;
}names has 3 entries
0 0 5 0 7 0
midThis pattern, an array indexed by an enum, is how you build lookup tables that stay correct when the enum changes. If someone reorders the enum, each string still lands in the slot of its name. The sparse array shows the zero-fill rule: only slots 2 and 4 were named, and the other four are zero. Add _Static_assert(sizeof names / sizeof names[0] == LEVEL_COUNT, "names out of sync") after the table so the build fails when a new level has no name.
Step 4: nested aggregates and arrays of structs
Designators chain, so you can reach into nested structs and arrays in one expression.
#include <stdio.h>
struct point { int x, y; };
struct shape {
const char *name;
struct point origin;
struct point corners[3];
};
int main(void) {
struct shape tri = {
.name = "triangle",
.origin.x = 1,
.origin.y = 2,
.corners = { [1] = { .x = 4, .y = 0 }, [2] = { .x = 0, .y = 3 } },
};
printf("%s at (%d,%d)\n", tri.name, tri.origin.x, tri.origin.y);
printf("corner1 (%d,%d) corner2 (%d,%d)\n",
tri.corners[1].x, tri.corners[1].y, tri.corners[2].x, tri.corners[2].y);
return 0;
}triangle at (1,2)
corner1 (4,0) corner2 (0,3)corners[0] is not named, so it is zero. The same technique builds tables of function pointers, configuration structs for drivers and arrays of test cases. For a one-off value you can use a compound literal, (struct point){ .x = 3, .y = 4 }, which creates an unnamed object, handy for passing a struct by value or by pointer to a function.
Step 5: know what it does not zero
The zero-fill guarantee covers members. It does not cover padding. C11 6.7.9p10 says that for an object with automatic storage and no initializer, padding is indeterminate, and for an initializer, the standard does not require padding bits to be zeroed. GCC and Clang usually do zero the padding for a brace initializer, but you cannot rely on that for a memcmp, a hash or a bytes-on-the-wire write of the struct. If you need identical bytes, clear the whole object first and then fill the fields:
#include <string.h>
struct record { char tag; int value; }; // 3 padding bytes after tag
void fill(struct record *r) {
memset(r, 0, sizeof *r);
r->tag = 'A';
r->value = 7;
}C23 adds the empty initializer = {}, which GCC and Clang already accepted as an extension, and which also zero-initializes. Use = {0} in code that must build with older standards. A related warning: the {0} idiom for a struct whose first member is itself a struct or array can trigger -Wmissing-braces in some compilers, and {} or a fully designated form avoids it.
Step 6: turn on the warnings that matter
Designated initializers are safe, but the surrounding mistakes still compile. Three flags help.
-Wextraenables-Wmissing-field-initializersin GCC, which warns when a positional initializer leaves fields out. It does not warn for designated initializers, because naming the fields is the intent.-Woverride-init, also part of-Wextra, warns when a designator overrides an earlier one in the same list, such as{ .port = 80, .port = 8080 }. The later value wins, and the warning catches copy-paste mistakes.Clang's
-Wmissing-field-initializersand-Winitializer-overridesdo the same jobs.
A reasonable baseline is -Wall -Wextra -Wuninitialized, with -Werror in CI after you have cleaned the existing warnings.
Step 7: portability notes
Designated initializers are standard C99 and later. They are not standard in C++ until C++20, and C++20 restricts them: designators must appear in declaration order, array designators are not allowed, and you cannot mix named and positional values. GCC and Clang accept the C-style forms in C++ as an extension with a warning under -Wpedantic. If a header is shared between C and C++, stick to in-order designators of plain fields.
MSVC supports designated initializers in C from Visual Studio 2019 version 16.8 with /std:c11 or /std:c17. Older toolchains reject them, which matters for libraries that still target them.
Using them in function calls and returns
A compound literal with designators lets you pass a configuration without declaring a named variable first, and it keeps call sites readable when a function takes a struct by value.
#include <stdio.h>
struct options {
int verbose;
int level;
const char *name;
};
static void run(struct options o) {
printf("verbose=%d level=%d name=%s\n", o.verbose, o.level, o.name ? o.name : "(none)");
}
int main(void) {
run((struct options){ .level = 3 });
run((struct options){ .verbose = 1, .name = "demo" });
return 0;
}verbose=0 level=3 name=(none)
verbose=1 level=0 name=demoEach call names only what differs from the defaults, and the rest is zero. That is a cheap way to get something like named arguments in C, and it keeps working when a field is added, because old call sites do not mention it. The convention works best when zero is a sensible default for every field, so design the struct that way: a verbose flag that defaults to off, a pointer that defaults to null meaning "use the built-in", a timeout of zero meaning "no timeout".
When designated initializers are the wrong tool
They fix a struct whose fields you set once at creation. They do not help when you build the struct in pieces over time, because the zero-fill happens only at the initializer. They also do not make a field mandatory: leaving out .host gives a null pointer, and the compiler stays silent. For required fields, either validate at the use site, or wrap creation in a constructor function that takes the required values as parameters and fills the optional ones from defaults. And for large tables of constants, a designated initializer in a static const array puts the data in read-only memory with no startup cost.


