Marko Kacanski
Marko Kacanski

Reputation: 433

Array doesn't initialize with a curly braces in c++

I'm learning c++ and I've encountered the following strange thing:

If I initialize array like the book says

int my_array[5] = {10}

every array field is still initialized to zero, when it should be ten.

If I initialize it in a loop, it works as intended

What is happening? I'm using Ubuntu and compiling with g++

Upvotes: 5

Views: 8858

Answers (3)

Trojan
Trojan

Reputation: 2254

When initialized with a list smaller than the array, only the specified elements are initialized as you expected; the rest are initialized to 0.

To initialize all values, use a loop, or std::fill_n, as shown here.

std::fill_n(my_array, 5, 10); // array name, size, value

Internally, std::fill_n is equivalent to a loop. From the first link:

template <class OutputIterator, class Size, class T>
    OutputIterator fill_n (OutputIterator first, Size n, const T& val)
{
    while (n>0) {
        *first = val;
        ++first; --n;
    }
    return first;     // since C++11
}

Upvotes: 6

user1508519
user1508519

Reputation:

The C++03 (assuming if you have an older version of GCC on an Ubuntu system) standard says:

8.5.1/7

If there are fewer initializers in the list than there are members in the aggregate, then each member not explicitly initialized shall be value-initialized (8.5).

And an array is an aggregate:

8.5.1/1

An aggregate is an array or a class (clause 9) with no user-declared constructors (12.1), no private or protected non-static data members (clause 11), no base classes (clause 10), and no virtual functions (10.3).

As to what value-initialized means:

To value-initialize an object of type T means:

— if T is a class type (clause 9) with a user-declared constructor (12.1), then the default constructor for T is called (and the initialization is ill-formed if T has no accessible default constructor);

... and skipping everything an int is not ...

— otherwise, the object is zero-initialized

Which is what happens for a variable of type int.

Upvotes: 7

Jarhmander
Jarhmander

Reputation: 344

What you observe is correct: the remaining items of the array are initialized to 0, according to the standard.

Upvotes: 11

Related Questions