Tuesday, September 21, 2010

Declaring Variables within Selection and Iteration Statements

In C++ (but not C), it is possible to declare a variable within the conditional expression
of an if or switch, within the conditional expression of a while loop, or within the
initialization portion of a for loop. A variable declared in one of these places has its
scope limited to the block of code controlled by that statement. For example, a variable
declared within a for loop will be local to that loop.
Here is an example that declares a variable within the initialization portion of a
for loop:
/* i is local to for loop; j is known outside loop. */
int j;
for(int i = 0; i<10; i++)
j = i * i;
/* i = 10; // *** Error *** -- i not known here! */
Here, i is declared within the initialization portion of the for and is used to control the
loop. Outside the loop, i is unknown.
Since often a loop control variable in a for is needed only by that loop, the
declaration of the variable in the initialization portion of the for is becoming common
practice. Remember, however, that this is not supported by C.
Whether a variable declared within the initialization portion of a for loop is local to
that loop has changed over time. Originally, the variable was available after the for.
However, Standard C++ restricts the variable to the scope of the for loop.
If your compiler fully complies with Standard C++, then you can also declare a
variable within any conditional expression, such as those used by the if or a while. For
example, this fragment,
if(int x = 20) {
x = x - y;
if(x>10) y = 0;
}
declares x and assigns it the value 20. Since this is a true value, the target of the if
executes. Variables declared within a conditional statement have their scope limited
to the block of code controlled by that statement. Thus, in this case, x is not known
outside the if. Frankly, not all programmers believe that declaring variables within
conditional statements is good practice, and this technique will not be used in
this book.

No comments:

Post a Comment