in this example, even though i will never use the variables WNDCLASSEX, x, y, cx, cy, they will still use memory when i’m in the message loop:
int WINAPI WinMain (HINSTANCE hInst, HINSTANCE hPrev, LPSTR lpArgs, int iCmdShow)
{
WNDCLASSEX wc;
...
RegisterClassEx(&wc);
const int cx = 640;
const int cy = 480;
// center of the screen
int x = (GetSystemMetrics(SM_CXSCREEN) - cx) / 2;
int y = (GetSystemMetrics(SM_CXSCREEN) - cy) / 2;
CreateWindow(..., x, y, cx, cy, ...);
MSG msg;
while (GetMessage(&msg, NULL, 0, 0) > 0)
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return 0;
}
But i’m wondering, if i put them in a scope, would they still use memory during the message loop? e.g.
int WINAPI WinMain (HINSTANCE hInst, HINSTANCE hPrev, LPSTR lpArgs, int iCmdShow)
{
{
WNDCLASSEX wc;
...
RegisterClassEx(&wc);
const int cx = 640;
const int cy = 480;
// center of the screen
int x = (GetSystemMetrics(SM_CXSCREEN) - cx) / 2;
int y = (GetSystemMetrics(SM_CXSCREEN) - cy) / 2;
CreateWindow(..., x, y, cx, cy, ...);
}
MSG msg;
while (GetMessage(&msg, NULL, 0, 0) > 0)
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return 0;
}
or maybe if i put them into two functions and called them in winmain e.g.
wnd_register(hInst);
wnd_create(hInst);
would that prevent them from using the memory?
The compiler has a lot of leeway for handling simple locals, like you have in your examples. They may live on the stack, they may only exist as immediate values in the machine code, or they may just live in registers. Stack space is usually allocated on entry to a function. The compiler will subtract some value from the stack pointer to make space for all the locals. On return of the function, the stack pointer is restored back to its original value. This is not usually done on exit of different scope blocks. Most compilers will try to aggressively reuse stack space as soon as variables are no longer used. In your example, it’d be perfectly legal for x and msg to have the exact same address on the stack, since their usage is non-overlapped.
My answer to this question goes into more detail on how local variables are allocated on the stack.
In your examples, the constants, cx and cy, most likely will have no memory backing them at runtime, and just be immediate values in the generated code. x and y will most likely live in registers until they need to be pushed on the stack for the call to CreateWindow. wc and msg will almost definitely be on the stack.
You shouldn’t worry about micro-optimizations at this level – let the compiler allocate space for local variables as it sees fit. You have a 1 MB stack by default, the amount of data consumed by these variables wouldn’t even register as noise. Spend your time worrying about more interesting problems instead.