Rule of thumb: variables should always be in - or as close as possible to - the scope where they are needed. Another way to phrase it is that variables should be enclosed inside the context in which they make sense and are actually useful.
Most often you will want to declare your incrementing variable along with the for
statement. Sometimes you will declare it a bit higher in the hierarchy because you need to know how many occurrences you looped through or at which point the loop was interrupted.
In almost all scenarios, having a loop increment variable declared as a class field is a bad idea. It won't give you any kind of additional "control"; if anything, it will only pollute your class and make it harder to figure out from an outsider's perspective. Plus, if you inadvertently use it in more than one loop, it may even break your code.
UPDATE:
About the latter, as keshlam explains very well in the comments below, a smaller scope will minimize the risk of your variable being modified where you wouldn't expect it. Plus, as he further explains, variables can safely free up used memory when going out of scope. Most modern languages will even do that for you automatically (your mileage may vary).
Also, since you asked what purpose could class-level variables serve, here are two examples in c# :
Property backends
This is likely the most popular use-case.
public class ConnectionHolder
{
// ...
IDbConnection _connection;
public IDbConnection Connection
{
get { return _connection; }
}
// ...
}
Holder of instance state information
Here we have the property in the above example accessing a factory that will in turn produce an instance of a IDbConnection
. The _connectionAccessed
boolean variable serves as a flag to tell if an attempt at getting ahold of a connection already has been made.
public class ConnectionHolder
{
// ...
bool _connectionAccessed = false;
IDbConnection _connection;
public IDbConnection Connection
{
get
{
if (!_connectionAccessed)
{
_connectionAccessed = true;
_connection = ConnectionFactory.Create();
}
return _connection;
}
}
// ...
}
As you can see in the two examples above it makes complete sense for the variables to be declared within full class scope.
I hope you find this information useful.