Michael Michael - 2 months ago 28
C Question

Avoiding null-initialized holes when using designated initializers

I have an enum like that:

enum {
ID_FOO = 0,

And a constant array using designated initializers like hat:

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

Now when I add a value to the enum, e.g. after
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.


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,
    // insert new values here


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.