In this tutorial, you will learn about C++ variable scope with examples.
In C++ Variable Scope is the part of the code or the portion where you can access a specific variable. It can be any type of variable in C++ but the variable scope will determine if you can use a variable somewhere or not. There are two types of Variables Scope in C++ which are:
- Global Scope
- Local Scope
A variable that is defined under the Global scope can be used anywhere in the code but a variable declared in a local scope or inside a block of code, can only be accessed inside that same block and will give an error in other parts of the program.
Global Scope
In Global Scope, the variable is usually declared outside the main function or outside any function. These types of variables fall under the global scope. When we write using namespace std
in our code, we are actually defining the std
in a global scope and specifying the compiler that we will be using that namespace for our program. A sample program to explain better is:
#include <iostream> using namespace std; int glob; // Declaring the Global Variable int main () { g = 10 // Initialization the global variable cout <<”The global variable value is : ”<<g; //Printing the global variable return 0; }
Output
Local Scope
In Local Scope, the variable is declared inside a function which can be the main function or any function. That variable can only be accessed inside that function and anywhere else will give an error. The use of local variables can be demonstrated by the following code.
#include <iostream> using namespace std; void func() { int loc=10; cout<<”Inside Function :”<<loc; } int main() { int loc=5; func(); cout<<”Inside Main :”<<loc; return 0; }
Output
Inside Main :5
Here you can see that though the variable name is the same, the local variable can be accessed inside their block and not outside. Each block defines the area inside which it recognizes the local variable.
Scope Resolution Operator
If you have a global and a local variable with the same name and you want to use that variable, the compiler will by default use the local variable unless you specifically tell the compiler to use the global variable. The following code will explain it better.
#include<iostream> using namespace std; int x = 5; // Global x int main() { int x = 10; // Local x cout << "Value of global x is " << ::x; cout<< "\nValue of local x is " << x; return 0; }
Output
Value of local x is 10<
This is how you can use the Scope resolution operator or ‘::’ to access a global variable that has the same name as the local variable inside a local block.