Local and Global Variables in C++

Local and Global Variables in C++ with Examples:

In this article, I am going to discuss Local and Global Variables in C++ Language with examples. Please read our previous article, where we discussed Function Return by Address and Reference in C++ with examples. Variables in any programming language plays an important role. The Variables in C++ are classified as Global variables and Local variables based on their scope. The main difference between them is that global variables can be accessed globally in the entire program, whereas the local variables can be accessed only within the function or block in which they are declared. Here, first, we will first understand what are the variables and scope, then we will discuss local variables and global variables, and finally, we will discuss the differences between them.

What is a Variable in C++?

The Variable in C++ is a name assigned to a storage area that the program can manipulate. A variable type determines the size of the variable’s memory. It is also used to determine the range of values that can be stored inside that memory location and the possible operations that can be applied to that variable.

What is a Scope?

A scope is a region of a program and the scope specified where a variable can be defined. The scope of the variable determines the lifetime of a variable. That means it is determined in which block of code the variable is applicable or alive. So, there are three places, where variables can be declared. They are as follows

  1. Variables declared inside a function or inside a block which is called local variables.
  2. Variables are declared inside the definition of function parameters which are called formal parameters.
  3. Variables declared outside of all functions are commonly called global variables.

The Local Variables in C++ can only be used by the statements which are inside that function or block of code.

Local Variables in C++

Local Variables in C++ are declared inside a function or inside a block. It can only be used inside the block where it is declared. The local variables are created when the function starts its execution and destroyed when the function completes its execution. So, the scope of the local variables is within the block where it is declared.
Example: For a better understanding, please have a look at the below code. Here, num1 and num2 are local variables as these two variables are declared inside the Addition function. These two variables can only be accessible inside the Addition function.

public int Addition(){
   int num1 =4;
   int num2 =5;
   return num1 +num2 ;
}
Advantages of using Local Variables in C++
  1. If several tasks change a single variable that is running simultaneously, then the result may be unpredictable. But declaring that variable as a local variable solves this issue as each task will create its own instance of the local variable.
  2. You can also give the same name to the local variables in different functions and this is possible because they are only recognized by the function they are declared.
  3. The Local variables are deleted as soon as the function completes its execution and hence release the memory space which it occupies.
Disadvantages of using Local Variables in C++
  1. It is a little bit difficult to debug a local variable.
  2. We need to pass the Common data repeatedly as data sharing is not possible between modules.
  3. They have a very limited scope i.e. within a block.
Global Variables in C++

The Global Variables in C++ are declared outside the function or block. It has a global scope means it holds its value throughout the lifetime of the program. Hence, it can be accessed throughout the program by any function defined within the program. The global variables are created when the program starts and destroyed only when the program ends.
Example: For a better understanding, please have a look at the below code. Here, num1 and num2 are global variables as these two variables are declared outside the function and blocks. These two variables can be accessible to any function and block defined in the program. Here, you can see that we are accessing these two variables inside the Addition function.

int num1 =4;
int num2=5;
public int Addition(){
   return num1 +num2;
}
Advantages of using Global variables in C++
  1. The global variables can be accessed from anywhere in the program.
  2. You just need to declare the global variables only once i.e. also outside of any function or block.
  3. The Global Variables are used for storing constants values that are going to be the same throughout the program.
  4. The Global variable is useful for data sharing i.e. when multiple functions are accessing the same data.
Disadvantages of using Global Variables in C++
  1. If we declared a large number of global variables, then they will remain in the memory till program execution is completed. This might cause of Out of Memory issues.
  2. The Data can be modified by any function. Any statement written in the program can change the value of the global variable. This may give unpredictable results in multi-tasking environments.
  3. If global variables are discontinued due to code refactoring, you will need to change all the modules where they are called.
Examples to Understand Local and Global Variables in C++

Global variables and local variables are commonly used terms in programming. Below we have a sample piece of code. Let us look at the below code and understand it and then we will show you the differences between them.

int g = 0;
void fun(){
     int a = 5;
     g = g + a;
     cout << g;
}
void main(){
     g = 15;
     fun();
     g++;
     cout << g;
}

Here we have the main function and there is no variable here but ‘g’ assigns ‘15’ so where is ‘g’? At the top of the code. It’s outside the function. It’s neither in ‘fun’ nor in ‘main’ function.

Can we have a variable outside all the functions? Yes, such variables are called Global Variables in C++. They are accessible in all the functions of a program. So ‘g’ is accessible in function fun and it is also accessible in function ‘main’, which means they can be used anywhere.

As we assigned 15 to ‘g’ so ‘g’ variable becomes 15. Then we call the function ‘fun’. Now function ‘fun’ has one variable that is ‘a’ which is assigned to ‘5’. ‘a’ belongs to function ‘fun’ and it is a local variable. We already know that local variables are allocated in the main memory where ever the function is called and deallocated wherever the function terminates. So, this variable is local to a function.

Next ‘g’ assigned ‘g+a’. So, this becomes 20. Then cout << g so 20 is displayed. Then function ‘fun’ ends and control come back to the main function. Then ‘g++’ statement will execute. So ‘g’ becomes 21. Next cout << g so 21 will be printed.

This was just a sample code that we have written to show you that the g variable can be accessed in any one of these functions. So ‘g’ is a global variable and a is a local variable. A variable inside the function is local and the variable outside all the functions is global.

Differences Between Local and Global Variables in C++

Now let us know the differences between Local and Global Variables in C++.

First, local variables are not accessible in other functions. They belong to that function only in which they are declared. Global variables are accessible in all the functions of a program.

Second, the local variables remain in the memory as long as the function is running. When the function ends. They are terminated. How long global variables are there, as long as the program is running, they are there in the memory.

Where the memory for the global variable is created? Is it inside the stack or inside the heap? No, memory for global variable is allocated inside the code section. Now let us write the complete program.

Program to understand Local and Global Variables in C++:
#include <iostream>
using namespace std;

int g = 0;
void fun()
{
    int a = 5;
    g = g + a;
    cout << g << endl;
}

int main()
{
    g = 15;
    fun ();
    g++;
    cout << g << endl;
}
Output:

Local and Global Variables in C++ with Examples

Differences Between Local variables and Global variables in C++
  1. The Local variables in C++ are declared inside a function whereas the Global variables in C++ are declared outside of the function body.
  2. The Local variables in C++ are created when the function is called i.e. when the function started its execution and the local variables will be destroyed as soon as the function completes its execution. On the other hand, the Global variables in C++ are created as soon as the program execution starts and is destroyed only when the program ends.
  3. The most important difference is that the Local variable doesn’t provide data sharing features whereas the Global variable provides data sharing i.e. the same data can be shared by multiple functions.
  4. Local variables in C++ are stored on the stack memory area whereas the Global variables in C++ are stored in a fixed location which is decided by the language compiler.
  5. Parameters passing is required for local variables i.e. we need to pass values while calling the method whereas it is not necessary for global variables.

Differences Between Local variables and Global variables in C++

In the next article, I am going to discuss Static Variables in C++ with Examples. Here, in this article, I try to explain Local and Global Variables in C++ Language with Examples. I hope you enjoy this Local and Global variable in C++ with Examples article. I would like to have your feedback. Please post your feedback, question, or comments about this article.

1 thought on “Local and Global Variables in C++”

  1. This article provides a clear explanation of local and global variables in C++. It’s essential to understand their differences in scope and memory management. Global variables offer data sharing capabilities, while local variables are limited to function scope. Great job on breaking down these concepts!

Leave a Reply

Your email address will not be published. Required fields are marked *