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?
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. ]
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.
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