Davide Andrea Davide Andrea - 2 months ago 5
C Question

Ensuring at compile time that all elements of a fixed size array are initialized

With an array of a specified size, the compiler warns me if I placed too many elements in the initialization:

int array[3] = {1,2,3,4}; // Warning


But, of course, it doesn't do so if I place too few elements (it just fills them with 0s):

int array[3] = {1,2}; // OK (no warning)


Yet, I MUST ensure at compile time that I specify exactly N elements in the initialization of an N-element array (it's an array of function pointers).

Can I have the compiler warn me if I specified too few elements?

Answer

First define your structure using your parameters, without specifying the size:

int array[] = { 1 , 2 , 3 };

Then simply check if the size of the created array is the same as N using _Static_assert:

_Static_assert( sizeof( array ) / sizeof( array[0] ) == N , "problem with array" );
Comments