Global and Static Variables in C++
Global and Static Variables in C++
PROGRAM:
#include <iostream>
Using namespace
std;
// Global variable
declaration Int c = 12;
Void test();
Int main()
{
++c;
// Outputs 13
Cout << c <<endl;
Test();
Return 0;
}
Void test()
{
++c;
// Outputs 14
Cout << c;
}
Output
13
14
𝘘 where c is a global variable.This variable is visible to both
functions main() and test() in the above program.
Global variable initialization
☆ Unlike local variables, which are uninitialized by default, variables
with static duration are zero-initialized by default.Non-constant
global variables can be optionally initialized:
Output
1
2
𝘘In the above program, test() function is invoked 2 times.
𝘘During the first call, variable var is declared as static variable and
initialized to 0. Then 1 is added to var which is displayed in the
screen.
𝘘When the function test() returns, variable var still exists because
it is a static variable.
𝘘During second function call, no new variable var is created. The
same var is increased by 1 and then displayed to the screen.
*Output of above program will be ( if var was not specified as
static variable)
1
1
☆Static Variables in C++ are the variables that remains always in the
memory.
☆They are just like a global Variable. Only the difference between
global and static variables is global variables can be accessed in any
function and static variables are accessible only inside the function in
which they are declared.
☆A static variable is not created every time we call a function. They
are just created only once which is at the loading time. Now let us
see the program for static variables.
Static variables Key Points
☆They have a local scope but remain in memory throughout the
execution of the program
• They are created in the code section
• They are history-sensitive
E-REFERENCE:
https://www.programiz.com/cpp-programming/storage-class
https://dotnettutorials.net/lesson/static-variables-in-cpp/
https://www.learncpp.com/cpp-tutorial/introduction-to-
global-variables/
Previous year question:
1.Compare the local and global variables in c++
programming with example.
#include<stdio.h> #include<stdio.h>
void main() int a=50, b=40;
{ void main()
int x=50, y=40; {
printf("x = %d and y=%d",x, printf("a = %d and
y); b=%d",a,b);
} }