Ensuring during compilation initialization of all elements of a fixed-size array

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

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

But of course, this is not the case if I put too few elements (it just fills them with 0s):

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

However, at compile time, I have to ensure that I precisely specify N elements in the initialization of an array of N-elements (this is an array of function pointers).

Can I warn the compiler if I specify too few elements?

+4
source share
1 answer

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

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

, N, _Static_assert:

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

Source: https://habr.com/ru/post/1655709/


All Articles