Neither approach is preferred.
Two common coding guidelines are (1) to ensure that no variable exists any longer than it needs to and (2) don't use a variable for more than one thing. Following such guidelines reduces (often, but not always, eliminates) accidental usage of a variable in a way that is not intended, and therefore helps avoid subtle programming errors.
In your first case, both i
and j
continue to exist until the end of the enclosing scope - which means they exist after the loops are complete. This maximises the chances of subsequent code (in that enclosing scope) accidentally reusing i
or j
for another purpose (e.g. when the intent is to use another variable). Such bugs are often hard to find.
The second case has the same problem, except with i
only. Even one variable with such a problem is bad news though.
I'd probably use a construct like
// unintentionally using i or j here will cause a compilation error
for (int i = 0; i < numRows; i++)
{
// unintentionally using j here will cause a compilation error
for (int j = 0; j < numCols; j++)
{
//
}
// unintentionally using j here will cause a compilation error
}
// unintentionally using i or j here will cause a compilation error
(The comments I've inserted to make the point make this more unreadable, but such comments will not normally be needed in practice).
This ensures that neither i
not j
exist outside the outer loop. It also means that j
cannot be accidentally used in the outer loop. Practically, it is easy to type i
when j
is intended (and vice versa) - for example, they are close together on a QWERTY keyboard. i
and j
also look quite similar visually, so visual code inspections often miss such errors. However, using an approach like this, the COMPILER will detect such typos. Given a choice, it is better to have a compiler pick up errors rather than for a human to have trouble finding them.
Of course, this doesn't prevent misuse or interchange of i
and j
in the inner loop - but that's one reason that guidelines often encourage use of more informative names than i
and j
- misuse of visually different names is easier for a mere mortal to detect.
No comments:
Post a Comment