C++ Global vs. Local Variable

The C++ programming language have scope set for variables depending on where it is declared. You can use variable with global scope anywhere in the program. The variable with local scope has limited scope. In this article, we will understand the difference between them and how to use them.

Advertisements

Global Variable

A global variable is not a special variable, but the scope of an ordinary variable. As mentioned earlier, variables are divided into global and local scope based on where they declared. The global variables are declared just below the header files. Once declared you can use them in:

  • Inside main function
  • Inside user-defined function
  • Inside another file of same program

For example,

// Header section
#include <iostream>
#include <ios>
//Global declaration section
int area = 0;

The variable area has a global scope now and you can use it anywhere in the program.

Advertisements

Local Variable

The local variable has limited scope such as a block or main function. If you want to perform some quick calculations in a block , declared a new variable just for the block. One interesting fact about global and local variable is than they can share same name of their scope are different.

Example Program:

//Gloabl vs. Local Variables
#include <cstdlib>
#include <iostream>
using namespace std;
// Gloabl declaration 
int area = 0;
int main()
{
    //Function declaration
    
    int area_rectangle();
    
    // call function area_rectangle();
    
    area = area_rectangle();
    
    //printing the results
    
    cout << "Area of Rectangle =" << area << endl;
    
    system("PAUSE");
    return EXIT_SUCCESS;
}
//finction definition area_rectangle()
int area_rectangle()
{
    //local variable declaration
    
    int area, length, breadth;
    
    //reading inputs 
    
    cout << "Enter value of Length:";
    cin >> length;
    
    cout << "Enter value of Breadth:";
    cin >> breadth;
    
    area = length * breadth;
    
    return(area);
}

Output:

Enter value of Length:10
Enter value of Breadth:35
Area of Rectangle =350

The above program computes area of a rectangle given its length and breadth. The variable area is declared in two places.

  • In the global declaration section
  • Locally inside the function

Since, the scope of both functions are different, they do not conflict with each other and C++ allows such declarations.

In the next lesson, we will learn about other built-in variable classification method called storage class.

Advertisements

Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.