Information Technology Reference
In-Depth Information
Scope of Variables in a for Statement
Any variables declared in the initializer are visible only within the for statement .
￿
This is different than C and C++.
￿
The following example illustrates this point:
Type is needed here for declaration
for( int i=0; i<10; i++ ) // Variable i is in scope here, and also
Statement ; // here within the statement.
// Here, after the statement, i no longer exists.
Type is needed here again because previous variable has gone out of existence
for( int i=0; i<10; i++ ) // We need to define a new variable i here, since
Statement ; // the previous one has gone out of existence.
The local variables declared within the body of the loop are known only within the loop.
Note Unlike C and C++, the scope of variables declared in the initializer lasts only for the length of
the loop.
Search WWH ::




Custom Search