it is acceptable to declare/define a variable in the WndProc function. as this code:
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
PAINTSTRUCT ps;
HDC hdc;
switch (message)
{
...
the question whether it’s good.
Because the program enters into this function, thousands of times every minute, and every time these variables are redefined, and again destroyed, maybe it is better to define these variables outside the WndProc function, in the class, thus saving time and resources?
As far as time and resources go, it makes little difference. These are local variables, stored on the stack. The entire stack is already reserved when your thread is created, and the memory for these variables is committed no later than the first time this procedure is executed. So this means that, for
switchconditions that don’t refer to these variables, you likely won’t be able to measure the difference in runtime or resource needs caused by the presence of the variables.Raymond points out that
WndProccan be called recusively. If you have a lot of local variables in yourWndProc, the resulting stack usage can be sub-optimal. I still can’t imagine any real world application where the bottleneck was stack usage ofWndProc.Having said that, a
WndProcmethod which is one big switch statement containing all the variables is bad practice. You don’t want to pollute the local namespace of this function with lots of different variables. I suggest you make a separate handler function for each message that you want to handle in the window procedure.Finally, you suggest declaring these variables in the class. Don’t do this. Local variables are always preferred where possible. It’s certainly going to be possible to declare these variables as locals. Although they should be locals of the separate handler functions that
WndProccalls.