Search code examples
cvariables

is it good or bad to reuse the variables?


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?


Solution

  • 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.