Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

c

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?

like image 201
Davide Andrea Avatar asked Mar 12 '23 01:03

Davide Andrea


1 Answers

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" );
like image 144
2501 Avatar answered Apr 28 '23 19:04

2501