user360907
user360907

Reputation:

Recycling variable name within single function

I have a function that contains two for loops, and I'm using a variable called count as the counter. I've chosen to recycle the name as the the first loop will finish it's execution completely before the second one begins, so there is no chance of the counters interfering with each other. The G++ compiler has taken exception to this via the following warning:

error: name lookup of ‘count’ changed for ISO ‘for’ scoping
note: (if you use ‘-fpermissive’ G++ will accept your code)

Is variable recycling considered bad practice in professional software development, or is it a situational concern, and what other implications have I missed here?

Upvotes: 2

Views: 307

Answers (4)

Thanatos
Thanatos

Reputation: 44256

Are you doing this?

for(int count = 0; ...)
{
    ...
}

for(count = 0; ...)
{
    ...
}

I doubt gcc would like that, as the second count isn't in scope. I think it only applies to the first for loop, but gcc has options to accept poor code. If you either make the second int count or move the first to the outer scope, gcc should be happy.

This depends on the circumstances, but I generally don't reuse variables. The name of the variable should reflect its purpose, and switching part way through a function can be confusing. Declare what you need, let the compiler take care of the optimizations.

Upvotes: 4

Lie Ryan
Lie Ryan

Reputation: 64847

If you're using a loop counter variables like this, then it usually doesn't matter.

for (int i ...; ... ; ...) { 
    ... 
}
for (int i ...; ... ; ...) { 
    ... 
}

however, if you're intending to shadow another variable:

int i ...;
for (int i ...; ... ; ...) { 
    ... 
}

that's a red flag.

Upvotes: 1

Jim Nutt
Jim Nutt

Reputation: 1756

It sounds like you're defining the variable in the for? i.e. "for (int count=0; count++; count < x)"? If so, that could be problematic, as well as unclear. If you're going to use it in a second for loop define it outside both loops.

Upvotes: 2

Skilldrick
Skilldrick

Reputation: 70819

Steve McConnell recommends not reusing local variables in functions in Code Complete.

He's not the definitive voice of practice in professional software development, but he's about as close as you're going to get to a definitive voice.

The argument is that it makes it harder to read the code.

What are you counting? Name the variables after that.

Upvotes: 2

Related Questions