Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing the first element in a struct

Tags:

c++

I do a lot of Win32 programming in C++ and many Win32 structures have a 'size' (often called cbSize or length) member as the first element which needs to be set before the relevant API call can be made. For example:

WINDOWPLACEMENT wp;
wp.length = sizeof(WINDOWPLACEMENT);
GetWindowPlacement(hWnd, &wp);

Now, I think it is good practice to initialize structure members to zero which I can do with:

WINDOWPLACEMENT wp = { };

or

WINDOWPLACEMENT wp = { 0 };

However, what happens to the other members of the struct if I initialize the first member like this:

WINDOWPLACEMENT wp = { sizeof(WINDOWPLACEMENT) };

Are they automatically initialized to zero? Or does it depend on which compiler I'm using and whether it's a debug build or not?

like image 417
Rob Avatar asked Mar 16 '11 19:03

Rob


2 Answers

Yes, they're automatically initialized to zero.

8.5.1/7:

If there are fewer initializers in the list than there are members in the aggregate, then each member not explicitly initialized shall be value-initialized (8.5). [Example:

struct S { int a; char* b; int c; };
S ss = { 1, "asdf" };

initializes ss.a with 1, ss.b with "asdf", and ss.c with the value of an expression of the form int(), that is, 0. ]

like image 171
Erik Avatar answered Oct 13 '22 03:10

Erik


If you are sure the size is the first element, this will be ok. Any members that don't get a value in the initializer will be zeroed.

like image 45
Bo Persson Avatar answered Oct 13 '22 01:10

Bo Persson