29

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?

Community
  • 1
  • 1
Adam Matan
  • 128,757
  • 147
  • 397
  • 562

2 Answers2

48

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
Jayen
  • 5,653
  • 2
  • 44
  • 65
Ed S.
  • 122,712
  • 22
  • 185
  • 265
5

No, it sets all members/elements that haven't been explicitly set to their default-initialisation value, which is zero for numeric types.

Marcelo Cantos
  • 181,030
  • 38
  • 327
  • 365