Which is preferred, method 1 or method 2?
Method 1:
LRESULT CALLBACK wpMainWindow(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam)
{
switch (msg)
{
case WM_PAINT:
{
HDC hdc;
PAINTSTRUCT ps;
RECT rc;
GetClientRect(hwnd, &rc);
hdc = BeginPaint(hwnd, &ps);
// drawing here
EndPaint(hwnd, &ps);
break;
}
default:
return DefWindowProc(hwnd, msg, wparam, lparam);
}
return 0;
}
Method 2:
LRESULT CALLBACK wpMainWindow(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam)
{
HDC hdc;
PAINTSTRUCT ps;
RECT rc;
switch (msg)
{
case WM_PAINT:
GetClientRect(hwnd, &rc);
hdc = BeginPaint(hwnd, &ps);
// drawing here
EndPaint(hwnd, &ps);
break;
default:
return DefWindowProc(hwnd, msg, wparam, lparam);
}
return 0;
}
In method 1, if msg = WM_PAINT when wpMainWindow function is called, does it allocate memory for all the variables on the stack at the beginning? or only when it enters the WM_PAINT scope?
Would method 1 only use the memory when the message is WM_PAINT, and method 2 would use the memory no matter what msg equaled?
Since it's the compiler's job to optimize my code, and an hour of compiler-time is way cheaper than an hour of my time, and my time gets wasted if I need to scroll up and down the code to see where a variable was declared, I think my company wants me to keep everything as local as possible.
Not even am I talking about 'the smallest block', but 'as near to the place where it is used'!
Memory allocation is not specified in the Standard to this detail, so for a real answer you'll have to specify compiler and platform. It's not going to matter for performance.
What you want is readability, and in general that's done by declaring variables in the smallest usable scope, and preferably when you can immediately initialize them with reasonable values. The smaller a variable's scope, the less it can potentially interact with the rest of the program in unpredictable ways. The closer the declaration to initialization, the less opportunity for anything bad to happen.
What would probably be better is something like
This is for C++. For C, the rule is similar, except that earlier versions of C required all the variables to be declared at the top of a block.
You can't know at what point the stack reservation is done.
For readability I would go with C99 (or C++). That allows you the declaration of a variable really there where first use it.