17

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;

  //..
  x = atoi(char_var);

  //..

  for (x=0; x<12; x++){
   //...
  }

  //..
  x = socket(...)
  if(x<0){
  //...
  }

  for(x=0;x<100;x++{
  //...
  }

  return 0;
}

Another variables could be used instead of x above (might be better for readability), but I wonder if it would provide me any benefit for the binary size, performance, or anything else?

9
  • 9
    for most cases it's bad. each variable should play its own role Jul 26, 2013 at 14:43
  • @AndreyChernukha What about a mere counter (e.g. i)
    – m0skit0
    Jul 26, 2013 at 14:44
  • 1
    @m0skit0 i said for most cases, not for all Jul 26, 2013 at 14:45
  • 1
    Using the same variable as a socket and a loop counter surely doesn't improve the readability of your code. Using meaningful variable names is also considered a good practice.
    – zakinster
    Jul 26, 2013 at 14:45
  • possible duplicate of is it acceptable to recycle or reuse variables?
    – Caleb
    Jul 26, 2013 at 15:12

9 Answers 9

24

In general it's very poor practice to reuse variable names for different purposes - if someone else needs to maintain your code later on the person will have to find these "context switches" in your code where x now suddenly means something other than what it meant before that line of code.

You may get some memory savings but that's so small compared to the problems it introduces that it's advised against. (Read the edit below, too.)

Typically it's also recommended not to use 1-character variable names for other than loop counters. One could argue that x could also be an X coordinate but I'd use some prefix or a longer name in that case. Single-letter variable names are too short to give meaningful hints about the purpose of a variable.

Edit: as several comments (and some of the other answers) pointed out, the potential memory savings (if any) depend on how good the compiler is. Well-written optimizing compilers may realize that two variables have no overlapping lifetimes so they only allocate one variable slot anyway. The end result would be no run-time gain and still less maintainable source code. This just reinforces the argument: don't reuse variables.

20
  • 5
    I don't think i for index is that bad.
    – Jiminion
    Jul 26, 2013 at 14:51
  • "You do get some memory savings" -- not if the compiler is good enough. Most compilers will optimize away a set of local variables that are each used over a different part of the function.
    – cdhowie
    Jul 26, 2013 at 14:51
  • @Jim For a loop counter / index it could be ok, although I usually use something like nIndex even for indices. I only ever use single-letter names for loop counters because of the above reasons. This also depends on personal practice to some extent.
    – xxbbcc
    Jul 26, 2013 at 14:52
  • @cdhowie Yes, you're right. I didn't write it that way because the programmer will perceive it as a saved slot. Also with reused variables it's unlikely that the entire variable could be eliminated. One would have write the code very carefully for that which is - in itself - a source of bugs then.
    – xxbbcc
    Jul 26, 2013 at 14:54
  • Do you re-use variable names the are declared in separate loops? Many are getting around this issue with declaring as local to the operation(s) as possible.
    – Jiminion
    Jul 26, 2013 at 15:00
8

As with almost everything in programming, it depends on the situation.

If you're reusing the same variable for different purposes, then it makes your code less readable and you shouldn't be doing it. If the purpose is the same (e.g. loop counters), then you can reuse with no problem since this isn't making your code less readable.

Reusing a variable will avoid reserving space in the stack, which results in a faster (you don't waste time reserving space in stack and pushing the value) and less memory consuming (you're not storing it in the stack) program. But this benefits are absolutely negligible in the whole program context, and also relative to architecture, language and compiler. So I would worry more about readability than this tiny benefits.

7

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.

3
  int x=0;

  //..
  x = atoi(char_var);

  //..
  int x = 0;

You cannot redeclare x in the same scope. If you are not redeclaring it but using it for different purposes, you are free to do this. But it's a bad practice and should be avoided as it decreases code readability. Also you should find meaningful names for your variables for the same reasons.

1
  • Thank you for the reply and explanation. Btw, I did not have intention to redecelerate it, it was just a copy pate mistake Jul 26, 2013 at 14:46
2

You can re-use it but i don't think it will bring a any significant benefit to your programm and it will make your code less readable.

2

Put it this way - how would you like it if I wrote a big pile of undocumented, complex code in such a way and, then, you get the job of maintaining/enhancing it.

Please do not do such a thing, ever :)

2

In general for any language, if you reuse variable names, and then you decide to refactor part of your code into another method, you end up having to add or edit declarations.

int i;
for(i = 0; i < 10; ++i) {
    printf("%d\t%d\n", i , i * i);
}
for(i = 0; i < 10; ++i) {
    printf("%d\t%d\n", i , i * i * i);
}

Suppose you take the second loop and move it to a print_cubes method. You will not be able to just cut and paste the for loop, as i will have no declaration there. A good IDE might be able to insert the declaration, but it might worry about the side-effects on i in the code you've typed.

In general, compilers can consolidate used variables by what are called graph-coloring algorithms. Consider this variant:

for(int i = 0; i < 10; ++i) {  // BLOCK 1
    printf("%d\t%d\n", i , i * i);
} // END BLOCK 1
for(int j = 0; j < 10; ++j) { // BLOCK 2
    printf("%d\t%d\n", j , j * j * j);
} // END BLOCK 2

The compiler lists the used variables: i, j. It lists the blocks being used: BLOCK 1, BLOCK 2. The parent function is also a block, but i and j are visible only in BLOCK 1 and BLOCK 2. So, it makes a graph of the variables, and connects them only if they are visible in the same block. It then tries to compute the minimum number of colors needed to color each vertex without giving two adjacent vertices the same color, similar to the Haken-Appel Four Color Theorem. Here; only one color is needed.

1

It is better to reuse variables in terms of memory. But be careful you don't need the value in a variable before reusing it. Other than that, you shouldn't use always the variable. It is important to keep a clean and readable code. So I advice you to choose different variable with names depending on the context so that your code don't become confusing.

You should also take a look at dynamic memory allocation in C, which is very useful to manage memory and variables.

https://en.wikipedia.org/wiki/C_dynamic_memory_allocation

3
  • An optimizing compiler will typically optimize away extra variables anyway, so reusing variables won't even save memory most of the time.
    – cdhowie
    Jul 26, 2013 at 14:50
  • Just FYI, local variables are not dynamically allocated.
    – m0skit0
    Jul 26, 2013 at 14:55
  • 1
    -1: Considering that compilers, whether they're optimising or not, usually work off an IR in single static assignment form where every time you assign a value to a variable, a "new" local variable is synthetised, reusing a name should make exactly no difference to the generated code.
    – millimoose
    Jul 29, 2013 at 12:59
-2

Only drawback is readability of your code.

Reusing variables you are saving memory.

Speed is not affected (unless you have to use more instructions in order to reuse variable).

3
  • 4
    Reusing variables will not save any memory if the compiler is good enough -- it is allowed to optimize away redundant variables as long as it can prove that usage does not overlap.
    – cdhowie
    Jul 26, 2013 at 14:48
  • 2
    Are you actually sure this isn't optimized out? It seems reasonable to me that a compiler could tell int x isn't referred to again in a function, and store the subsequent int y in that memory.
    – djechlin
    Jul 26, 2013 at 14:48
  • 1
    -1: No you are not saving memory. Read about static single assignment form - the compiler IR makes no difference between reassigning to an existing variable and assigning to a new one. What matters is the overlap in lifetime between versions of a variable. When optimizing, the compiler will use as much memory as is needed for the maximum overlap. When not optimizing, the compiler will actually use a new memory location for every subexpression - you can see this using the -G0 flag to gcc.
    – millimoose
    Jul 29, 2013 at 13:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.