Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Have compiler check the number of array initializers

Initializing an array (in C++, but any solution which works for C will likely work here as well) with less initializers than it has elements is perfectly legal:

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

However, this can be a source of obscure bugs. Is there a way to have the compiler (gcc) check the number of initializers for one specific array, and emit a warning or even an error if declared and actual size don't match?

I know I can use int array[] = { 1, 2, 3 }; and could then use static assertions involving sizeof(array) to verify my expectation there. But I'm using array in other translation units, so I have to declare it with an explicit size. So this trick won't work for me.

like image 950
MvG Avatar asked Mar 07 '13 11:03

MvG


People also ask

What are array Initializers?

The initializer for an array is a comma-separated list of constant expressions enclosed in braces ( { } ). The initializer is preceded by an equal sign ( = ). You do not need to initialize all elements in an array.

What is too many initializers?

too many initializers. The number of initializers exceeds the number of objects to be initialized. The compiler can deduce the correct assignment of initializers to objects and inner objects when inner braces are elided from the initializer list.

What happens when an array is initialized with more Initializers as compared to its size?

If the array is longer than the initializer list, the array elements without an explicit initializer are initialized to 0. The number of values in the initializer list may never be greater than the number of elements in the array. But it's okay if the array is larger than the number of initializer values.


1 Answers

(promoted from a comment as requested)

If the values in the array are important to the correct functionality of the system, and having zero-initialized values at the end causes bugs, then I would just add a unit test to verify the array contains the right data, instead of trying to enforce it in the code.

like image 82
Jonathan Wakely Avatar answered Oct 01 '22 13:10

Jonathan Wakely