Scope of variables in C++






Variables in C++ can also be classified depending on their scopes. Scope means the region or the part of the program where the variable
is defined. So depending on the scope, variables can be classified into following types:

  • Local variables
  • Global variables
  • Extern variables
  • Static variables

Now let's see some details about these.


Local Variables:

Those variables which are defined inside a function or a specific code block(ex. if-else block, do-while, for block, etc.) is known as a local
variable. The lifetime or visibility of that variable is only within inside that function or block. We cannot access it from outside the block, if
we try to do so then the compiler will throw an error.

For all local variables compiler will allocate the space in the stack part of the memory. These variables will get automatically created
whenever the function/block inside which it is defined, will come into execution. And after that when the control of execution comes out of
that function/block, then local variables will automatically get destroyed and its reserved memory space is freed from the

Let's see some example from the code.

              
                // Demo code for local variables 
                #include < iostream>
                using namespace std;
                void CelciusToFarenheit(int temp) 
                { 
                  // variable local to function CelciusToFarenheit()
                  int temp_farenheit = 0; 

                  temp_farenheit = (temp * 1.8) + 32; 
                  cout << "Farenheit value is : " << temp_farenheit; 
                } 

                // main function 
                int main() 
                { 
                  // variable local to function main()
                  int temp_celcius = 0; 

                  cout << "Celcius value is : " << temp_celcius << "\n"; 
                  CelciusToFarenheit(temp_celcius); 
                  return 0;
                } 
              
            

The output will be:

              
                Celcius value is : 0
                Farenheit value is : 32
              
            

Now if we see in the above code example, varaible "temp_celcius" is local to function main() and variable "temp_farenheit" local to function CelciusToFarenheit(). So these are accessible only inside their respective functions.
If we try to access the variable "temp_farenheit" from main function or variable "temp_celcius" from CelciusToFarenheit function, then it will compilation error.


Global varaibles:

Global variables are those variables that are defined outside of all the functions usually at the start of the program and are accessible by all
functions. These variables are not affected by the function or block scope and will hold their value till the lifetime of the program. Any
functions can access the global variables throughout the entire program after its declaration.
Global variables will get stored in the "Data Segment" part of the memory and will get destroyed or its memory space is freed only at the end
of execution of the program.

Below is the example of the global varaible.

              
                // Demo code for global variables 
                #include < iostream>
                using namespace std;

                // global variable declaration
                int val_global = 0; 

                int main () 
                {
                  // local variables declaration
                  int value_1, value_2;
                   
                  value_1 = 500;
                  value_2 = 300;
                  val_global = value_1 + value_2;
                    
                  cout << "Value of global variable is:"<< val_global;
                  return 0;
                }    
              
            

The output will be:

              
                Value of global variable is:800
              
            

Now we also have to note that if in our program we are having the global variable and local variable of similar name then the local variable
will get the precedence over the global variable when we try to access them.

Check the example code below.

              
                #include < iostream>
                using namespace std;

                // global variable 
                int val = 100; 

                int main () 
                {
                  // local variable of same name as gloal variable
                  int val = 200;
                                       
                  cout << "Value of val is:"<< val;
                  return 0;
                }    
              
            

The output will be:

              
                Value of val is:200
              
            

Here "val" is the name of local as well as global variable. But when we try to print its value from the main() function, it will give the priority
to the local variable instead of the global one and will print its value that is "200".


Static variables:

Whenever we require a the variable will not be created again and it will hold or retain its value throughout the program than we have to
use the "static" keyword with our variables. In simple words, the static variable will be created only once and after that, the same copy of
it will be used throughout the program instead of creating new variables. This will also save the memory overhead.

Let's first check a simple program of the static variable.

              
                // Demo code for static variables 
                #include < iostream>
                using namespace std;
                //! Function having static variable
                void static_func()
                {
                  //! Static variabel definition
                  static int static_count=0;
                  cout << static_count++;
                }

                //! Normal Function without static variable
                void non_static_func()
                {
                  int count=0;
                  cout << count++;
                }

                int main()
                {
                  cout << "Non-Static Function Output:";
                  for(int i=0;i< 5;i++)
                  {
                    non_static_func();
                  }
                  cout << endl <<"Static Function Output:";
                  for(int i=0;i< 5;i++)
                  {
                    static_func();
                  }
                  return 0;
                }
              
            

The output will be:

              
                Non-Static Function Output: 00000
                Static Function Output: 01234
              
            

Here we can see that in the function without static variable the output is 5 times 0's. This the because form inside the side the for loop
whenever the function is called then in each iteration variable "count" is created and get initialized to zero.
But on the other hand, in the case of the static variable "static_count", is created only once when the function "static_func()" was called
first time and after that, the same copy of the variable will get updated with new a value on further function calls. That's why its value
will be incremented on each iteration of the for loop.

Some characteristics of the static variables are:

  • A static variable can be decleared as either a global or local variable.
  • Global static variable have file scope. It can only be accessible within the file where it is created.
  • While creating a local static variable, it should be assigned with an initial value, else it's default value will be 0.
  • Local static variable can maintain its value from one function call to another and it will retain the value till the end of the program execution.
  • Unlike normal variable where memort allocation is done in stack, the memory alloction for static variables will be done in the data segment part.

Extern variables:

Sometime we need to share the variables between two different files. For example suppose our project contains multiple files and we
have defined a variable in one of the file. Now we need to access the same variable in other files also. So here comes in picture the
"extern varaibles". We can define a variable using the "extern" keyword. We can simply say the extern variables as a global variable
accessible from multiple files.

Syntax for defining a extern variable:
extern < data-type> < variable-name> = value;
Ex. extern int value = 10;