Michael Michael - 27 days ago 15
C Question

Avoiding null-initialized holes when using designated initializers

I have an enum like that:

enum {
ID_FOO = 0,
ID_BAR,
ID_BAZ
}


And a constant array using designated initializers like hat:

char* arr[] = {
[ID_FOO] = "foo stuff",
[ID_BAR] = "bar stuff",
[ID_BAZ] = "baz stuff",
0
}


Now when I add a value to the enum, e.g. after
ID_FOO
but forget to add it to the array, then I would get an uninitialized null-initialized 'hole' in the array. Is there any way to prevent that, or at least get a warning from the compiler?

A non-portable GCC-only solution is fine.

Answer

One way is to add a sentinel maximum value to your enum, which you can use to verify that this maximum value is the same as the number of elements in the array.

enum {
    ID_FOO = 0,
    ID_BAR,
    ID_BAZ,
    // insert new values here

    ID_MAX
}

assert(ID_MAX == (sizeof(arr)/sizeof(arr[0]) - 1));

This is a runtime check; have a look at C compiler asserts - how to implement? for ideas on how to get a compile-time error instead.

Comments