2

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?

1
  • It's not just what's given, you can even mix and match: godbolt.org/z/zs8es5 This is weird. Commented Oct 20, 2020 at 21:43

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.