Chapter 3 Variable Scoope
Chapter 3 Variable Scoope
UNIVERSITY
Chapter 3:
Variable Scope
www.Khurasan.edu.af- [email protected]
Variable Scope
• A scope is a region of the program and broadly speaking there are
two places, where variables can be declared −
• Inside a function or a block which is called local variables,
• Outside of all functions which is called global variables.
www.Khurasan.edu.af- [email protected]
Local Variables
• Variables that are declared inside a function or block are local
variables. They can be used only by statements that are inside that
function or block of code.
#include <iostream>
using namespace std;
main(){
//a is local to main function, it cannot be accessed outside
int a = 10; //of main function
if(a == 10){
int b = 200; //b is local to if block, it cannot be accessed
cout<<a; //outside of the if block
} else{
cout<<b;
}
}
www.Khurasan.edu.af- [email protected]
Global Variables
• Global variables are defined outside of all the functions, usually
on top of the program. The global variables will hold their value
throughout the life-time of your program.
#include <iostream>
using namespace std;
// Global variable declaration:
int g;
main () {
// Local variable declaration:
int a, b;
// actual initialization
a = 10;
b = 20;
g = a + b;
cout << g;}
www.Khurasan.edu.af- [email protected]
NOTE
• A program can have same name for local and global variables but value of local variable
inside a function will take preference. For example
#include <iostream>
using namespace std;
// Global variable declaration:
int g = 20;
main () {
// Local variable declaration:
int g = 10;
cout << g; //if you want the value of global variable
//then use scope resolution operator e.g.
cout <<::g; //mean global variable
}
www.Khurasan.edu.af- [email protected]
Initializing Local and Global Variables
• When a local variable is defined, it is not initialized by the system, you
must initialize it yourself. Global variables are initialized automatically
by the system when you define them as follows −
Data Type Initializer
int 0
char '\0'
float 0
double 0
pointer NULL
www.Khurasan.edu.af- [email protected]