Filling structs question

Hi all.
This is how I initialize the WNDCLASSEX struct and every other struct
1
2
3
4
5
6
7
8
9
10
11
12
13
WNDCLASSEX wc;
wc.cbClsExtra = 0;
wc.cbSize = sizeof(WNDCLASSEX);
wc.cbWndExtra = 0;
wc.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
wc.hCursor = LoadCursor(0, IDC_ARROW);
wc.hIcon = LoadIcon(0, IDI_APPLICATION);
wc.hIconSm = 0;
wc.hInstance = hInstance;
wc.lpfnWndProc = WndProc;
wc.lpszClassName = L"MainWindowClass";
wc.lpszMenuName = L"MainMenu";
wc.style = 0;


But I'm thinking this might not be a good idea. If they add more members to the struct in the future the application might not be able to run. So ZeroMemory() might be the best way to do it. That way even if they add more members, ZeroMemory() takes care of that.
Is this the main reason why most people use ZeroMemory()?

If you are wondering why I have initialized WNDCLASSEX like this, it's for performance reasons. With ZeroMemory() you initialize every byte of the struct with 0, and in addition to that you write a second time to the members that will be non zero, like for example the lpfnWndProc, hIcon members etc..
If you initialize the struct like I have you only write to each struct member only once, so I'm thinking it may be faster, even though it may not be noticable at all

So what do you guys think, is this a good way to initialize structs?

Last edited on
I always do this:
WNDCLASSEX wc = 0;

All members is automatically filled with zero by the compiler. If the struct changes there is no problem, the compiler knows about it. You only need to fill the struct members that you want.


There could be cases whrn using ZeroMemory (or memset) could crash your program.
@modoran
i think you though of
WNDCLASSEX wc = {0};
I wouldn't worry too much.
In the case of WNDCLASSEX you got WNDCLASSEX::cbSize.

If you fill that member like you did in your code, the windows API should get it right.
Registered users can post here. Sign in or register to post.