C++ float array initialization

arrays, c++, floating-point, initialization

Solution

You only initialize the first N positions to the values in braces and all others are initialized to 0. In this case, N is the number of arguments you passed to the initialization list, i.e.,

float arr1[10] = { };       // all elements are 0
float arr2[10] = { 0 };     // all elements are 0
float arr3[10] = { 1 };     // first element is 1, all others are 0
float arr4[10] = { 1, 2 };  // first element is 1, second is 2, all others are 0

Problem

Possible Duplicate: C and C++ : Partial initialization of automatic structure While reading Code Complete, I came across an C++ array initialization example: ``` float studentGrades[ MAX_STUDENTS ] = { 0.0 }; ``` I did not know C++ could initialize the entire array, so I've tested it: ``` #include <iostream> using namespace std; int main() { const int MAX_STUDENTS=4; float studentGrades[ MAX_STUDENTS ] = { 0.0 }; for (int i=0; i<MAX_STUDENTS; i++) { cout << i << " " << studentGrades[i] << '\n'; } return 0; } ``` The program gave the expected results: ``` 0 0 1 0 2 0 3 0 ``` But changing the initialization value from `0.0` to, say, `9.9`: ``` float studentGrades[ MAX_STUDENTS ] = { 9.9 }; ``` Gave the interesting result: ``` 0 9.9 1 0 2 0 3 0 ``` Does the initialization declaration set only the first element in the array?

Original source

Related problems