What are global variables in C++?


Global variables are defined outside of all the functions, usually on top of the program. The global variables will hold their value throughout the lifetime of your program.

A global variable can be accessed by any function. That is, a global variable is available for use throughout your entire program after its declaration. 

Example

#include <iostream>
using namespace std;
// Global variable declaration:
int g;
int main () {
   // Local variable declaration:
   int a, b;
   a = 10;
   b = 20;
   g = a + b;
   cout << g;
   return 0;
}

Output

This will give the output −

30

Lakshmi Srinivas
Lakshmi Srinivas

Programmer / Analyst / Technician

Updated on: 11-Feb-2020

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements