A variable can be defined anywhere in the code. It's scope begins when it is defined and ends when the block that it is defined in ends.
Ex:
#include <iostream>
using namespace std ;
int main()
{
int x1 ;
x1 = 10 ;
{ //A
int x2 ;
x2 = 20 ;
} //B
cout << x1 << endl ;
//Compiler error as x1 has gone out of scope
//cout << x2 << endl ;
return( 1 ) ;
}
We have the integer variable defined at comment //A that is "x2" . This is where the scope starts and at comment //B the scope ends. So if we try to use the variable "x2" after that we run into a compiler error. The variable "x1" retains it's scope till the end of the main function. A function can have 2 variables
with the same name as long as the names are in different scope.
Ex:
#include <iostream>
using namespace std ;
//Global variable
int x1 = 200 ;
//-----------------------------------------------------------
int main()
{
int x1 ; //A
x1 = 10 ;
{ //B
int x1 ;
x1 = 20 ;
cout << x1 << endl ;
} //C
cout << x1 << endl ;
cout << ::x1 << endl ; //D
return( 1 ) ;
}
//-----------------------------------------------------------
Output:
20
10
200
A variable that is defined outside a function is called a global variable. In the example above we have the global variable "x1" and the main function has 2 local variables ; both named x1 .
The inner block has x1 printed out and that prints 20 . Then the next printout is of the "x1" that is defined at comment "A" . and the very last statement at comment "D" prints out the global variable "x1" . We can prepend a variable with double colons and that means we are referring to the global variable.
Is there a way for us to refer to the x1 defined at comment "A" from the inner block starting at comment "B" ? Unfortunately not. We can only refer to the global variables with the same name.
A function's parameter variables have the same scope as local variables.
Ex:
#include <iostream>
using namespace std ;
void func1( int param1 ) //A
{
} //C
//-----------------------------------------------------------
int main()
{
int x1 = 10 ;
func1( x1 ) ;
return( 0 ) ;
}
//-----------------------------------------------------------
the function "func1" has a parameter named "param1" . What is the scope of "param1" ? The scope is from the line at which it is declared to the end of the function ( comment "C" ) . We cannot define another variable with the same name in the scope.
Ex:
#include <iostream>
using namespace std ;
void func1( int param1 ) //A
{
int param1 ; //B
} //C
//-----------------------------------------------------------
int main()
{
int x1 = 10 ;
func1( x1 ) ;
return( 0 ) ;
}
//-----------------------------------------------------------
The above code will not compile because the variable defined "param1" at comment "B" falls in the same scope as the variable "param1" defined at comment "A" .