Local & Global Variables in C++

A scope is a region of the program where they can access.

there are three spots, where variables can be declared −

  • Inside a function or a block which is named local variables,
  • In the definition of function parameters which is named formal parameters.
  • Outside of all functions which is named global variables.

Local Variables

Variables that are declared inside a function or block are local variables. They can be used only by statements that are inside that function or block of code. Local variables aren't known to functions outside their own. Following is the example using local variables −

#include <iostream>
using namespace std;

int  main() {
//Local Variable Declaration
int a, b;

int c;

//intialization
a = 10;
b = 20;
c = a + b;

cout << c;

return 0;
}

Output:
30

Global Variables

Global variables are defined outside of all the functions, usually on top of the program. The global variables will hold their value throughout the life-time 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. Following is the example using global and local variables −

#include <iostream>
using namespace std;

//Global Variable Declaration
int g;

int  main() {
//Local Variable Declaration
int a, b;

//intialization
a = 10;
b = 20;
g = a + b;

cout << g;

return 0;
}

Output:
30

Local & Global Variable with Same Name

A program can have same name for local and global variables but value of local variable inside a function will take preference. For example −

#include <iostream>
using namespace std;

//Global Variable Declaration
int g = 20;

int  main() {
//Local Variable Declaration
int g = 10;

cout << g;

return 0;
}

When the above code is compiled and executed, it produces the following result −

Output:
10