I understand that there is many different ways to accomplish the same thing in C++; however, I would like to know the differences between these methods of initializing a struct. I would also like to know what is the C++ way of doing things, as I know some of these methods are from C.
struct MyStruct
{
int x, y, z;
};
MyStruct s1 = { 0 }; //I think this is from C but not really sure.
MyStruct s2 = { }; //I think this might be from C++
MyStruct s3 = { sizeof(MyStruct) } ; //Not sure where this comes from but I like it
When programming in C++, which should I use?
MyStruct s3 = { sizeof(MyStruct) } ;
is very unlikely to do what you think it does:
struct MyStruct
{
int a;
int b;
};
In this example, MyStruct s3 = { sizeof(MyStruct) } ;
will initialize x3.a
to 8 and x3.b
to 0.
(Assuming POD types, not the new uniform-initialization syntax)
The three are valid initializations in C++ assuming that the struct has a first element that can be initialized from an integer. The third option sets the first member of the struct to the size of the struct, and the rest of the fields are left zero-initialized.
The first two are equivalent in C++, although the second one is not valid C, as in C you must pass at least one value inside the braces.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With