Scope of a variable x++ Programming language
Table of Content:
What is scope of a variable?
The scope of a variable defines the area in the code where an item can be accessed.
- Instance variables are declared in class declarations, and can be accessed from any methods in the class or from methods that extend the class.
- Local variables can be accessed only in the block where they were defined.
// An example of how variable scopes work. class ScopeExample { // The variable a is declared within the class. int a; // Because the method below is declared within the class, // it can access all the variables defined within the class. void aNewMethod() { // The variable b is declared within the method. // It can only be accessed by this method. int b; } }
Loop Scope
Loop Scope: Variables declared in a loop have loop scope. They are accessible only within the loop where they are declared.
void myMethod() { for (int i = 0; i < 5; i++) { int loopVar = i; // loopVar has loop scope } // loopVar is not accessible here }