Initialization of a normal array with one default value


C++ Notes: Array Initialization has a nice list over initialization of arrays. I have a

int array[100] = {-1};

expecting it to be full with -1's but its not, only first value is and the rest are 0's mixed with random values.

The code

int array[100] = {0};

works just fine and sets each element to 0.

What am I missing here.. Can't one initialize it if the value isn't zero ?

2: Is the default initialization (as above ) faster than the usual loop through the whole array and assign a value or does it do the same thing?

5/7/2016 11:13:42 AM

Accepted Answer

Using the syntax that you used,

int array[100] = {-1};

says "set the first element to -1 and the rest to 0" since all omitted elements are set to 0.

In C++, to set them all to -1, you can use something like std::fill_n (from <algorithm>):

std::fill_n(array, 100, -1);

In portable C, you have to roll your own loop. There are compiler-extensions or you can depend on implementation-defined behavior as a shortcut if that's acceptable.

11/8/2017 11:21:12 PM

There is an extension to the gcc compiler which allows the syntax:

int array[100] = { [0 ... 99] = -1 };

This would set all of the elements to -1.

This is known as "Designated Initializers" see here for further information.

Note this isn't implemented for the gcc c++ compiler.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow