Declare variables at top of function or in separate scopes?

后端 未结 9 1116
温柔的废话
温柔的废话 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条回答
  •  失恋的感觉
    2020-12-01 01:51

    For Java programming language, the common practice is to declare local variables only when needed in a method.

    void foo(int i) {
      if (i == 1)
        return;
      Map map1 = new HashMap();
      if (i == 2)
        return;
      Map map2 = new HashMap();
    }
    

    For C++ programming language, I also suggest the same practice since declaring variables with a non-trivial constructor involves execution cost. Putting all these declarations at the method beginning causes unneeded cost if some of these variables will be used.

    void foo(int i) 
    {
      if (i == 1)
        return;
      std::map map1; // constructor is executed here
      if (i == 2)
        return;
      std::map map2; // constructor is executed here
    }
    

    For C, the story is different. It depends on architecture and compiler. For x86 and GCC, putting all the declarations at function beginning and declaring variables only when needed have the same performance. The reason is that C variables don't have a constructor. And the effect on stack memory allocation by these two approaches is the same. Here is an example:

    void foo(int i)
    {
      int m[50];
      int n[50];
      switch (i) {
        case 0:
          break;
        case 1:
          break;
        default:
          break;
      }
    }
    
    void bar(int i) 
    {
      int m[50];
      switch (i) {
        case 0:
          break;
        case 1:
          break;
        default:
          break;
      }
      int n[50];
    }
    

    For both functions, the assembly code for stack manipulation is:

    pushl   %ebp
    movl    %esp, %ebp
    subl    $400, %esp
    

    Putting all the declarations at function beginning is common in Linux kernel code.

提交回复
热议问题