Failed to register window when using local WNDCLASSEX variable

309 Views Asked by At

If I put the WNDCLASSEX wcex variable definition out of main function (as global variable) the class will be registered successfully

#include <windows.h>
WNDCLASSEX wcex;
int main()
{
    wcex.cbSize = sizeof ( WNDCLASSEX );
    wcex.lpszClassName = "Success" ;

    if ( !RegisterClassEx ( &wcex ) )
    {
        MessageBox ( NULL, "Failed to register window class.", "Error", MB_OK );
    }
}

But If I put it inside the main function, It will not be registered

#include <windows.h>
int main()
{
    WNDCLASSEX wcex;
    wcex.cbSize = sizeof ( WNDCLASSEX );
    wcex.lpszClassName = "Success" ;

    if ( !RegisterClassEx ( &wcex ) )
    {
        MessageBox ( NULL, "Failed to register window class.", "Error", MB_OK );
    }
}

I can't figure out the reason, kindly help in this issue. Thanks in advance.

1

There are 1 best solutions below

6
IInspectable On

Objects with static storage duration are zero-initialized1). Your second example is semantically different in that wcex (automatic storage duration) holds random values. To match the semantics, use WNDCLASSEX wcex = { 0 }; instead.


1) Assuming you are using a C++ compiler. The rules for C are different.