TOPIC: Global Variables and Local Variables
In the continuation of C++ programming, we will discuss about the
Global Variables and the Local Variables.
But first of all, let us understand what a variable is.
A variable is a name which acts as a storage location or
container where different values can be manipulated.
Now we will discuss about Global Variables. Global Variables are
the variables which are declared before the main function of the
program.
If we declare a variable globally, we can access it from any part
of the program. They remain in memory throughout the runtime of
the program. The values cannot be changed by any other function.
But in contrary to this, Local Variables are the variables which
are declared in the main function of the program. The user can
provide different values during the runtime of a program.
NB:
→ We can accept the values of a variable using the Insertion
operator.
→ But we can also initialize the variable with a fix value, for
example x = 10.
Good Software like wine, takes time
- Joel Spolsky
C++ Program
Code written in Visual Studio Code
// Program to illustrate the Global and Local Variables declaration
#include<iostream>
using namespace std;
int glob; // this is global variable declaration
int main()
{
int a = 8, b = 2; // this is local variable declaration
glob = a + b;
cout<< glob;
return 0;
}
10
C++ Program
#include<iostream>
using namespace std;
int glo = 6;
void sum()
{
int a;
cout << glo;
}
int main()
{
int glo = 10;
glo = 121;
int a = 10, b = 5;
float pi = 3.14;
char c = 'y';
bool t = true;
sum();
cout << glo << endl << true << endl;
cout << "\nHere the value of a is " << a << "\nThe value of b is " << b;
cout << "\nThe value of pi is " << pi;
cout << "\nThe value of c is " << c;
getch();
return 0;
}