While writing code you need various variables. Variables have their own boundaries where those are accessible. Outside those boundaries variables don’t hold their values. These boundaries are known as scope of variable. It is important to know the lifetime and scope of variables. The Variables Scope can be divided into two categories:
- Global Variables
- Local Variables
Global variables
Global variables are variables that are often declared outside the main()
function. The variable scope is the full file where the variable is defined. The global variable can be defined as below:
//include a header file from Standard Library #include using namespace std; //This is GLOBAL VARIABLE int weight; //the work of the program starts from function called main int main() { weight = 3; //Now weight is equal to 3 cout << "Weight is " << weight << endl; cin.ignore(); return 0; }
You will understand better the Global Variable Scope when you will learn functions and more advanced C++ topics. For you now it’s more important to understand the meaning of the local variable.
Local Variables
Global variables are accessible in full file. But local variables are not accessible in full file. The local variable’s scope is between the block of instruction that is defined between “{” and “}”. Take a look on this example:
int main() { { double price = 2.0, height = 3.1, length = 2.4; cout << "Price is " << price << endl; cout << "Length is " << length << endl; cout << "Height is " << height << endl; } weight = 3; //Now weight is equal to 3 cin.ignore(); return 0; }
As you can see, price, height and length are defined in a separate block in the main function. And all the operations are performed in the same block. Try to run this program. It will be executed without any problems. Now, modify our program in the following way:
int main() { { double price = 2.0, height = 3.1, length = 2.4; cout << "Price is " << price << endl; cout << "Length is " << length << endl; cout << "Height is " << height << endl; } weight = 3; //Now weight is equal to 3 cout << "Price is " << price << endl; cout << "Length is " << length<< endl; cout << "Height is " << height<< endl; cin.ignore(); return 0; }
We are trying to use variables that are declared in a block outside of this block. This leads to the following errors:
As a conclusion of this article, we have to understand that local variables are seen only inside the block, where it is declared. You can’t use local variable outside the block where it is declared.