Declare variables at top of function or in separate scopes?

后端 未结 9 1140
温柔的废话
温柔的废话 2020-12-01 01:47

Which is preferred, method 1 or method 2?

Method 1:

LRESULT CALLBACK wpMainWindow(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam)
{
    switch (         


        
9条回答
  •  旧时难觅i
    2020-12-01 02:14

    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'!

    LRESULT CALLBACK wpMainWindow(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam) 
    { 
        switch (msg) 
        { 
            case WM_PAINT: 
            { 
                RECT rc; 
                GetClientRect(hwnd, &rc);            
    
                { // sometimes I even create an arbitrary block 
                  // to show correlated statements.
                  // as a side-effect, the compiler may not need to allocate space for 
                  // variables declared here...
                  PAINTSTRUCT ps; 
                  HDC hdc = BeginPaint(hwnd, &ps); 
                  // drawing here 
                  EndPaint(hwnd, &ps); 
                }
                break; 
            } 
            default:  
                return DefWindowProc(hwnd, msg, wparam, lparam); 
        } 
        return 0; 
    } 
    

提交回复
热议问题