Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 16

GLOBAL VARIABLES

☆ A Global variable is declared outside any function and is accessible


to all routines in the program.
☆ It can be accessed from anywhere in the entire program and
usually declared at the top or start of the program outside of all
blocks and functions of the program.
☆ It can be accessed from any function without any error.
☆ The global variables get defined outside any function- usually at
the very top of a program.
☆ The variables hold their actual values throughout the lifetime of
that program, and one can access them inside any function that gets
defined for that program.
☆ We can use global variables for many purposes such as for storing
constant literal as that improves our program’s consistency.
☆ We can access global variables from any function in a program, we
need to declare them only once, which shortens our code.
☆ To define a global variable in C++,we can declare global—that is,
nonlocal—variables by declaring them outside of any function
definition.
☆ It’s usually best to put all global declarations near the beginning of
the program, before the first function. A variable is recognized only
from the point it is declared, to the end of the file.
☆ If a variable is defined outside all functions, then it is called a
global variable.
𝘘The scope of a global variable is the whole program. It can be
used and changed at any part of the program after its declaration.It's
life ends only when the program ends.

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:

Int g_x; // no explicit initializer (zero-initialized by default)


Int g_y {}; // value initialized (resulting in zero-initialization)
Int g_z { 1 }; // list initialized with specific value
The scope of global variables
☆ Identifiers declared in the global namespace have global
namespace scope (commonly called global scope,informally
called file scope), which means they are visible from the point of
declaration until the end of the file in which they are declared.
𝘘Once declared, a global variable can be used anywhere in the file
from that point onward.In the above example, global variable g_x
is used in both functions doSomething() and main().
☆ Global variables can also be defined inside a user-defined
namespace. g_x has been moved from the global scope into user-
defined namespace Foo.
#include <iostream>
Namespace Foo // Foo is defined in the global scope
{
Int g_x {}; // g_x is now inside the Foo namespace, but is still a
global variable
}
Void doSomething()
{
// global variables can be seen and used everywhere in the file
Foo::g_x = 3;
Std::cout << Foo::g_x << ‘\n’;
}
Int main()
{
doSomething();
std::cout << Foo::g_x << ‘\n’;
// global variables can be seen and used everywhere in the file
Foo::g_x = 5;
Std::cout << Foo::g_x << ‘\n’;
Return 0;
}
𝘘 The identifier g_x is now limited to the scope of namespace Foo,
that name is still globally accessible (via Foo::g_x), and g_x is still a
global variable.

Advantages of using Global variables in C++


𝘘The global variables can be accessed from anywhere in the
program.we need to declare the global variables only once
* i.e. also outside of any function or block.
𝘘The Global Variables are used for storing constants values that are
going to be the same throughout the program.
𝘘The Global variable is useful for data sharing i.e. when multiple
functions are accessing the same data.
Disadvantages of using Global Variables in C++
𝘘If we declared a large number of global variables, then they will
remain in the memory till program execution is completed.
𝘘This might cause of Out of Memory issues.
𝘘The Data can be modified by any function. Any statement written
in the program can change the value of the global variable.
𝘘This may give unpredictable results in multi-tasking environments.
𝘘If global variables are discontinued due to code refactoring, you
will need to change all the modules where they are called.
STATIC VARIABLES

☆A static variable is a variable that is declared using the


keyword static.
☆ The space for the static variable is allocated only one time and
this is used for the entirety of the program. Once this variable is
declared, it exists till the program executes.
☆Static variables can also be declared at local scope.
☆Static duration means that the object or variable is allocated when
the program starts and is deallocated when the program ends.
☆The static keyword can be used to declare variables and functions
at global scope, namespace scope, and class scope
☆ Mostly static variables are used to grab the common properties
that are shared by the class objects such as the name of the
department for a college class, etc.
☆ These variables are allocated memory only once when the class is
loaded.
☆ We can put static members (Functions or Variables) in C++ classes.
For the static variables, we have to initialize them after defining the
class.
☆To initialize we have to use the class name then scope resolution
operator (::), then the variable name. Now we can assign some value.
☆ When the static keyword is used with global variables and
functions, it limits their scope to the current file. This implies that
static global variables or functions are accessible only within the file
they are declared in.
☆ Keyword static is used for specifying a static variable.
𝘘 For example;
Int main()
{
Static float a;
... .. ...
}
☆ A static local variable exists only inside a function where it is
declared (similar to a local variable) but its lifetime starts when the
function is called and ends only when the program ends.
☆The main difference between local variable and static variable is
that, the value of static variable persists the end of the program.
PROGRAM:
#include <iostream>
Using namespace std;
Void test()
{
// var is a static
variable Static int var =
0;
++var;
Cout << var << endl;
}
Int main()
Test();
Test();
Return 0;
}

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

When to use Static Variable in C++?


☆ We should use a static variable whenever we want to reuse the
modified value of the variable inside a function in the next function
call.
☆When we want all the objects to maintain a single copy of the class
variable.
Advantages of using static variables in C++
★Memory efficiency: Now we don’t need to create an instance for
accessing the static members, so it saves memory.
★ It belongs to the type, so it will not get memory each time when
the instance is created.
★Direct addressing.
★No run-time overhead for allocation and de-allocation.
Disadvantages of using static variables in c++
★Cannot support recursive.
★storage cannot be shared among variable.
★size of data objects must be known at compile time.
★Data structures cannot be created dynamically.

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.

LOCAL VARIABLE GLOBAL VARIABLE


Variables that are Global variables are those
declared within or inside a variables which are declared
function block are known outside of all the functions or
as Local variables. block and can be accessed
globally in a program.
The scope is limited and The scope remains
remains within the function throughout the program.
only in which they are
declared.
For example: For 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);
} }

In the above example, we In the above example, a


have declared x and y and b are the global
two variables inside the variables.
main function. Hence
these are
local variables.
Any change in the local Any change in global
variable does not variable affects the whole
affect other functions program, wherever it is
of the being used.
program.
A local variable is A global variable exists in
created when the the program for the entire
function is time
executed, and once the the program is executed.
execution is finished,
the variable is
destroyed.
It can only be accessed by It can be accessed
the function statements throughout the program
in by all the functions present
which it is declared and in the program.
not by the other functions.
Local variables are stored in a Global variables are stored in
stack in memory. the data segment of memory
If the local variable is not If the global variable is not
initialized, it takes the initialized, it takes zero by
garbage value by default.
default.
We can declare various We cannot declare
variables with the same many variables with the
name but in other functions. same name.
Local variables are stored in Global variables are stored
a stack in memory . in the data segment of
Memory.

You might also like