Declare variables at top of function or in separate scopes?

后端 未结 9 1113
温柔的废话
温柔的废话 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 02:03

    Whether something's allocated on the stack in case 1 is implementation defined. Implementations aren't even required to have a stack.

    It's usually no slower to do so since the operation tends to be a simple subtraction (for a downward growing stack) of one value from the stack pointer for the entire local variable area.

    The thing that's important here is that the scope should be as local as possible. In other words, declare your variables as late as possible and only keep them around as long as needed.

    Note that declaring here is at a different abstraction level to allocating space for them. The actual space may be allocated at the start of the function (implementation level) but you can only use those variables while they're scoped (C level).

    Locality of information is important, just like its cousin, encapsulation.

提交回复
热议问题