Structure initialization, huh?!

Can someone explain what this code means? Because I have no idea. I was playing around with structs and found out I can do this...
and does the word 'mystruc' even matter? because if I take it out nothing happens. Did I just create a struc called strucName with an int at value 9? and then what if a few lines down I repeat the code with a different int value but same struct name....

1
2
3
4
struct mystruc
{
     int x;
} strucName = {9};
that say nothing about initializer lists! Anyway, any structure or class can be initialized with a so-called "brace-enclosed initializer list" (in your case the 9 within the braces), where the values inside represent the memebers of the structure, in the same order they are declared inside the structure instantation.
closed account (zb0S216C)
Initialisation lists, such as the one used to initialise strucName, is used to initialise each member of the instance. For instance:

1
2
3
4
5
struct X
{
    int a_;
    float f_;
} x_ = {1, 2.0f};

The first piece of data in the initialiser-list will be used to initialise x_.a_; the second piece of data will be used to initialise x_.f_. This is only available for POD (Plain Old Data) types.

turtlemaster wrote:
"and does the word 'mystruc' even matter?"

Yes, since that's the type-identifier. You need it for future instantiations. However, if you plan on creating only 1 instance, then you can safely omit it.

turtlemaster wrote:
"and then what if a few lines down I repeat the code with a different int value but same struct name...."

That would result in an error, even with std::initializer_list.

Wazzak
Thanks for your responses ^__^
Last edited on
Topic archived. No new replies allowed.