is it good or bad to reuse the variables?

后端 未结 9 2051
灰色年华
灰色年华 2020-12-17 15:03

I wonder if it is good or bad (or does not matter) if I reuse the variable names as much as possible? for example

int main(void){
  //...
  int x=0;

  //..
         


        
9条回答
  •  星月不相逢
    2020-12-17 15:26

    Bad. For simple types like ints, passed by value, the compiler will be able to figure out when they are unneeded and reuse the space.

    For example, I compiled the following C++ code in Visual Studio 2010 using 32-bit Release mode:

    for (int i = 0; i < 4; ++i)
    {
        printf("%d\n", i);
    }
    
    for (int j = 0; j < 4; ++j)
    {
        printf("%d\n", j);
    }
    

    and got the following assembler output:

    ; 5    :    for (int i = 0; i < 4; ++i)
    
        mov edi, DWORD PTR __imp__printf
        xor esi, esi
        npad    6
    $LL6@main:
    
    ; 6    :    {
    ; 7    :        printf("%d\n", i);
    
        push    esi
        push    OFFSET ??_C@_03PMGGPEJJ@?$CFd?6?$AA@
        call    edi
        inc esi
        add esp, 8
        cmp esi, 4
        jl  SHORT $LL6@main
    
    ; 8    :    }
    ; 9    : 
    ; 10   :    for (int j = 0; j < 4; ++j)
    
        xor esi, esi
    $LL3@main:
    
    ; 11   :    {
    ; 12   :        printf("%d\n", j);
    
        push    esi
        push    OFFSET ??_C@_03PMGGPEJJ@?$CFd?6?$AA@
        call    edi
        inc esi
        add esp, 8
        cmp esi, 4
        jl  SHORT $LL3@main
    
    ; 13   :    }
    

    You can see that the compiler is using the esi register for both i and j.

提交回复
热议问题