26

可能重复:
C 和 C++:自动结构的部分初始化

在阅读Code Complete时,我遇到了一个 C++ 数组初始化示例:

float studentGrades[ MAX_STUDENTS ] = { 0.0 };

我不知道 C++ 可以初始化整个数组,所以我测试了它:

#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;
}

该程序给出了预期的结果:

0 0
1 0
2 0
3 0

但是将初始化值从更改0.0为,例如9.9

float studentGrades[ MAX_STUDENTS ] = { 9.9 };

给出了有趣的结果:

0 9.9
1 0
2 0
3 0

初始化声明是否仅设置数组中的第一个元素?

4

2 回答 2

41

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
于 2012-10-08T22:29:09.923 回答
5

不,它将所有未明确设置为默认初始化值的成员/元素设置为数字类型为零。

于 2012-10-08T22:14:36.700 回答