for loops
In C++, you will often see a for
loop counter defined right
inside the for expression:
for(int j = 0; j < 100; j++) {
cout << "j = " << j << endl;
}
for(int i = 0; i < 100; i++)
cout << "i = " << i << endl;
The statements above are important
special cases, which cause confusion to new C++ programmers.
The variables i and j are
defined directly inside the for expression (which you cannot do in C).
They are then available for use in the for loop. It’s a very
convenient syntax because the context removes all question about the purpose of
i and j, so you don’t need to use such ungainly names as
i_loop_counter for clarity.
However, some confusion may result if you
expect the lifetimes of the variables i and j to extend beyond the
scope of the for loop – they do
not[39].
Chapter 3 points out that while
and switch statements also allow the definition of objects in their
control expressions, although this usage seems far less important than with the
for loop.
Watch out for local variables that
hide
variables from the enclosing scope. In general, using the same name for a nested
variable and a variable that is global to that scope is confusing and error
prone[40].
I find small scopes an indicator of good
design. If you have several pages for a single function, perhaps you’re
trying to do too much with that function. More granular functions are not only
more useful, but it’s also easier to find
bugs.