Say you have some basic code where similar operations will take place in nearby lexical scopes. Take for example some simple pseudo code:

variable = "foo"
# Do something with variable
if (True) {
    variable = "bar"
    # Do something else with variable
for i in range 1..100 {
    variable = i
    # Do another thing with variable

Say that in each scope, the variable is used for a distinct, but similar task and thus the name "variable" is appropriate in each case. What is the best practice in this case for naming? Should you use the name "variable" each time? Increment the name such as "variable1", "variable2", etc.? Or something else entirely?

  • 2
    one may argue that conceptually, this has been addressed in How would you know if you've written readable and easily maintainable code? If your peers keep complaining about your way of doing things, be it one way or another, you better change to make them feel better – gnat Feb 18 '15 at 20:47
  • @gnat I definitely agree that if people are complaining you should change your code to meet the majority standards. I ask because I wrote similar code where a variable was named the same way multiple times and I may be the only one to look at this code for awhile. No one complains, but I would like to write my code in the best form the first time. – jkeuhlen Feb 18 '15 at 20:55
  • Different names for different things. Don't go giving the same name to a string and an integer. I'm ok with giving the same name to two things in the same scope if the code would be correct regardless of which of the two the variable points to. – Doval Feb 18 '15 at 20:57
  • 1
    You create confussion. In the other hand you save... urgh... nothing. – Tulains Córdova Feb 19 '15 at 8:52

If the variable in question represents the same thing for both functions, I can't see why it would be a problem. If you're arbitrarily using variable to mean "any variable within a function that can do anything" then yes, it is a problem. Name your variables in the context to which they are used.

  • Between functions, I agree that this is trivially the case. But I wasn't sure if this is still the case in nearby lexical scopes. – jkeuhlen Feb 18 '15 at 20:57
  • I would say it applies to all code in general. – Lawrence Aiello Feb 18 '15 at 20:57
  • This is, after all, the whole point of variable scopes. (Or really namespacing/scoping in general.) – Jörg W Mittag Feb 18 '15 at 22:58

There are two entirely different things at play here: variable reuse and variable name reuse (redeclaration.) Your sample pseudocode does not make it clear which one of the two cases you are referring to, so I will mention both.

This is variable reuse:

int i = 5;
for( ;; )
    i = 3;

This is variable name reuse:

int i = 5;
for( ;; )
    int i = 3;

Variable reuse is very, very bad and it should be avoided at all costs because it leads to spaghetti code. Code may one day be added after the for loop, expecting i to hold 5, and it may be very shocked to find out that it doesn't. People reading this code will assume that you are replacing the value of i in order to use the new value after the loop. Decent compilers will give you a "variable reuse" or "variable scope too broad" warning if you do this, but they may not always be able to detect it, (in the case of a for loop, they cannot, because you may be doing it intentionally,) so it is best to not push your luck.

Variable name reuse is perfectly fine, and as a matter of fact desirable under certain scenarios. For example, variable name reuse guarantees that within the for loop you cannot accidentally refer to the outer scope i, because it has been redefined and therefore it is now inaccessible. (Unfortunately C# does not like that, but most other languages have no problem with it.)

I would not answer "it is good or bad depending on what your peers say", because you may be asking this question on stackoverflow precisely in order to have arguments when discussing this matter with your peers.

  • There are situations in which variable reuse is not a bad thing. Suppose you're writing code to setup columns in a grid. The description of the column must be looked up, so ideally you save it to a variable to prevent looking up the value multiple times in declaration of that column description (assume you must use it more than once). It would make little sense to use a separate variable to hold the lookup for the 2nd, 3rd, ... nth column. If you can generalize to a function, better still, but not always possible. Very specific case, again. Otherwise good answer. – Neil Feb 19 '15 at 8:47

If the variable is something simple and clear, like i, count, sum, go ahead and reuse it.

If the variable is central to the method, like calculatedResult, or you are in a series of if/else blocks (or blocks all ending in return calculatedResult), reuse it.

But if the blocks are not mutually exclusive, and control flows from one to the other, it might be clearer to not reuse the same variable name. For example, if you are doing a series of SQL queries, I might go (Java-ish syntax)

if (theyCareAboutPeople) {
   peopleQuery = "SELECT * FROM people WHERE blah blah...";
   ResultSet people = mySqlDriver.execute(peopleQuery);
   // do something with people
if (theyCareAboutAges) {
   ageQuery = "SELECT * FROM ages WHERE blah blah...";
   ResultSet ages= mySqlDriver.execute(ageQuery );
   // do something with ages

Note that I used meaningful names, like "peopleQuery" and "ages", instead of calling all the queries "query" and all the results "result". IMO, this is slightly clearer, but YMMV.


Reusing a variable is bad, because a compiler that would normally warn you about uninitialised variables etc. can't warn you, because at the time of the second use, the variable will be initialised.

Reusing a variable name is usually not a problem.

You may get compiler warnings if you create a variable with the same name as another variable in an outer scope. With good reason, because that is going to be confusing and error prone. Avoid it whether you get warnings or not.

You may have problems with a debugger that thinks there is a dozen variables with the same name and cannot tell you which one you are using right now. This is a problem of the debugger and should be fixed, but if you run into the situation, you may choose to write code that is more debugger friendly.


Specificity - don't use a variable named variable unless it refers to something specific, like variable timing on an engine. Just don't do it.

In a given context:

Do not re-use variable names in a given context for different purposes. In a function, don't make variable = 'foo' for use as a string then later in the function make variable a numerical index in a loop - that's bad practice and will return to bite you in a big way.

You can re-use variable names in a given context for the same generic purpose, but consider using a new variable to avoid confusion:

var i, j, myarray = [];
for( i = 0; i < 100; i++){
   mayarray.push[ i ];

for( j = 0; j < 1000; j++){
   // something with j

You could technically re-use i for the second loop instead of using a new variable, j, but I would avoid re-use in this case because it can lead to confusion reading the code and could introduce bugs later on.

Outside the same context

We all re-use common variable names like i for loop indexes; that is good practice and improves readability as long as they are not in the same context.

If you are thinking about re-using a non-generic variable name, like partNumber, limit their re-use to places where they refer to the same logical thing in your code as other uses of the variable. Otherwise it can lead to confusion in your code.

Your application has a schema internally that shows the data you are manipulating. Map that schema to your variable names, use generic variable names for generic purposes, and be aware of your contexts for variable re-use.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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