The difference between different structure initialization methods

I understand that there are many different ways to do the same in C ++; however, I would like to know the differences between these structure initialization methods. I would also like to know what C ++ is - a way of doing things, as I know that some of these methods are taken 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?

+4
source share
5 answers

(Assuming POD types, not the new syntax syntax)

Three valid initializations in C ++, assuming that the structure has the first element that can be initialized from the whole. The third parameter sets the size of the structure for the first member of the structure, and the remaining fields remain zero.

The first two are equivalent in C ++, although the second is not valid C, as in C, you must pass at least one value inside curly braces.

+3
source

MyStruct s3 = { sizeof(MyStruct) } ; unlikely to do what you think:

 struct MyStruct { int a; int b; }; 

In this example, MyStruct s3 = { sizeof(MyStruct) } ; initializes x3.a to 8 and x3.b to 0.

+5
source

[Assuming C ++] For s1, you initialize the first variable in MyStruct to zero. For s3, you initialize it to the size of the structure. In both cases, the compiler converts your provided value to the type of the first variable in MyStruct.

0
source
 MyStruct s1 = { 0 }; 

Using this king of initialization, you initialize the first element of the structure. If the value does not match the type of the element, the compiler (for example, gcc or g ++) will try to make some implicit translation. All other items will be set to the default value.

 MyStruct s3 = { sizeof(MyStruct) }; 

- this is the same, the first value of the element will be the size of the structure in bytes.

 MyStruct s2 = { }; 

Finally, this initialization is valid only in C ++, the equivalent in C is MyStruct s2; . It initializes all default values.

0
source

The first initializes the elements of the structures to zero, and its pointers to zero in C. http://www.ex-parrot.com/~chris/random/initialise.html and Initialize / reset struct to zero / null

But not in C ++. In C ++, the first element is initialized.

 MyStruct s1 = { 0 }; //I think this is from C but not really sure. 

The second is initialized to zero in C ++, for example: 1) for C

 MyStruct s2 = { }; 

The third sets the value of the first element in sizeof MyStruct in C and in C ++

 MyStruct s3 = { sizeof(MyStruct) } ; //Not sure where this comes from but I like it 
0
source

All Articles