Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between different struct initialization methods

Tags:

c++

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?

like image 526
Haywire Spark Avatar asked Feb 18 '23 20:02

Haywire Spark


2 Answers

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.

like image 107
fredoverflow Avatar answered Apr 30 '23 15:04

fredoverflow


(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.

like image 29
David Rodríguez - dribeas Avatar answered Apr 30 '23 14:04

David Rodríguez - dribeas