Dan
Dan

Reputation: 627

Correct way of initialing an array within a struct in C++

Assume this code:

#include <iostream>

struct test {
 int a[3];
 float b[2];
};

I can init the array in both these ways:

int main(){
 test t = {{1,2,3}, {1.0,2.0}};
 return 0;
}

or

int main(){
 test t = {1, 2, 3, 1.0, 2.0};
 return 0;
}

How is the second approach even compiling? is the compiler picking each value and putting in an array slot in order?

Upvotes: 2

Views: 71

Answers (1)

cigien
cigien

Reputation: 60440

The second snippet is perfectly valid as described in aggregate initialization:

The braces around the nested initializer lists may be elided (omitted), in which case as many initializer clauses as necessary are used to initialize every member or element of the corresponding subaggregate, and the subsequent initializer clauses are used to initialize the following members of the object. ...

Since test is an aggregate, composed of subaggregates a and b, omitting the nested braces results in the first 3 elements being used to initialize a, and the remaining 2 elements being used to initialize b.

Upvotes: 5

Related Questions