Scope

From CompSciWiki
Jump to: navigation, search

COMP 1010 Home > Loops


Introduction

Scope is a term that refers to the lifetime or visibility of a variable. Variables declared in the test condition of a loop only exist in the scope of that loop. The loop's scope is the block of code that is contained between the opening "{" after the test condition, and the closing "}" (remember a do-while loop is different, the test condition is located after the closing bracket). After the loop ends, any variables initialized inside the loop are said to be out of scope, meaning they can not be accessed by any code found outside the loop.

Scope of a Loop

The scope of a loop in java is defined by the braces '{' and '}' as with all blocks of code. Scope is not only important for defining what code will execute but also important to declared variables. For example, if you were to define the variable " int i " in a for loop (see below) that variable will only exist within the scope of the loop. If we were to try and access the variable " i " outside the scope of the loop we would get an error. This is because Java sees that the loop has finished executing and will throw away any variables that were initialized inside the loop.

 for ( int i = 0 ; i < ''somevalue'' ; i++ )
{
     // statements
}
// The following line of code will produce an error as the variable " ''i'' " is only defined inside the loop.
i = 7; 

This is similar for nested loops as well

 for( int i = 0 ; i < 10 ; i++ )
{
    j=j+1; //this is not valid. j is not defined here
 
    for( int j=0 ; j < 10 ; j++ )
    {
        i=i+1;  //this is valid, although you should never change the control variable inside the loop
    }
 
    j=j+1;  //this is also not valid. j is not defined here
} 

Summary

Knowing the scope of loops is important to understanding when and why you can use certain variables. The use of the variable declared inside the for loop, as seen above, can cause problems. If you need access to the variable outside the loop, be sure to declare the variable outside the scope of the loop. Usually you would declare it with the rest of the variables at the beginning of your code so as to follow proper coding standards and guidelines.

Previous Page: Nested Loops Next Page: Infinite Loops