I\'m trying to initialize an int array with everything set at -1.
I tried the following, but it doesn\'t work. It only sets the first value at -1.
in
The reason that int directory[100] = {-1}
doesn't work is because of what happens with array initialization.
All array elements that are not initialized explicitly are initialized implicitly the same way as objects that have static storage duration.
int
s which are implicitly initialized are:
initialized to unsigned zero
All array elements that are not initialized explicitly are initialized implicitly the same way as objects that have static storage duration.
C++11 introduced begin and end which are specialized for arrays!
This means that given an array (not just a pointer), like your directory
you can use fill as has been suggested in several answers:
fill(begin(directory), end(directory), -1)
Let's say that you write code like this, but then decide to reuse the functionality after having forgotten how you implemented it, but you decided to change the size of directory
to 60. If you'd written code using begin
and end
then you're done.
If on the other hand you'd done this: then you'd better remember to change that 100 to a 60 as well or you'll get undefined behavior.fill(directory, directory + 100, -1)