4

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?

Davide Andrea
  • 1,357
  • 2
  • 15
  • 39
  • 4
    You can omit the number, then use a `static_assert` to check the size ... – o11c Sep 24 '16 at 18:23
  • 2
    Such as (MSVC) `_STATIC_ASSERT(sizeof arr / sizeof arr[0] == 3);` The man page says "Evaluate an expression at compile time and generate an error when the result is FALSE." But you must omit the array `[length]` as stated above. – Weather Vane Sep 24 '16 at 18:52
  • @o11c: That's indeed a nice idea! Why not made that an answer? Does not work if you use designated initialisers and skip some fields, though. – too honest for this site Sep 24 '16 at 19:48
  • @WeatherVane: What is `_STATIC_ASSERT`? That is certainly non-standard (and uses a name reserved for the standard itself) – too honest for this site Sep 24 '16 at 19:51
  • @Olaf as I wrote, I was showing what MSVC does. It is a [macro](https://msdn.microsoft.com/en-us/library/bb918086.aspx). Whatever your opinion is about MSVC, I don't really care. – Weather Vane Sep 24 '16 at 19:53

1 Answers1

7

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" );
2501
  • 25,460
  • 4
  • 47
  • 87