3. VARIABLES
VARIABLES ARE DECLARED INSIDE A BLOCK HAVE
BLOCKSCOPE.BLOCK SCOPE VARIABLES CAN ONLY BE
ACCESSED WITHIN THE BLOCK IN WHICH THE BLOCK THEY
ARE DECLARED(OR A NESTED SUB-BLOCK),AND ARE
DESTROYED WHEN THE BLOCK ENDS.
4. Variables declared outside of a
block are called global
variables. Global varaiables
have program scope,which
means they can be accessed
every where in the program and
they are destroyed when the
program ends.
5. Example
Ing_nx;//global variable
Int main( )
{
Int ny; //local variable ny
// global vars can be seen every where in program
//so we can change their values here
g_nx=5;
}//ny is destroyed here
6. Because global variables have
program scope,they can be
used across multiple files.In the
section on progaram with
multiple files,you learned that in
order to use a function declared
in another file,you have to use a
forward declaration,or a header
file.
7. Similarly,in order to use a global
variable that has been declared in
another file,you have to use a
forward declaration or a header
file,along with extern
keyword.Extern tells the computer
that you are not declaring a new
variable,but instead referring to a
variable declared else where.
8. Here is an example of using a
forward declaration style
extern:
Global.cpp:
//declaration of g_value
Int g n Value=5;
main.cpp
//extern tells the compiler this variable is
declared elsewhere
Extern int g _n Value;
9. Int main()
{
g_n Value=7;
return 0;
}
Here is an example of using a header file
extern:
global.cpp:
//declaration of g_nValue
Int g_nValue=5;
global.h:
10. #ifndef GLOBAL_H//header guards
#define GLOBAL_H
//extern tells the compiler this variable is
declared elsewhere
extern int g_value
# end if
main.cpp:
# include “global.h”
Int main()
{g_nValue=7;
Return 0;
}
11. Generally speaking,if a global
variable is going to be be
used in more than 2 files,it’s
better to use the header file
aapproach.Some
programmers place all of a
programs global variables in a
header file named globals.h
to be included by other .cpp
files that need to use them.
12. Local variables with the same
name as a global variables
hide the global variable inside
that block.However,the global
scope operator(::) can be
used to tell the compiler you
mean the global variable
version:
13. Int nValue=5
int main( )
{int n Value=7;//hides the
global n Value
variable
n Value++;//increments
local n Value,not
global nValue
14. :: nValue--;//decrements
global nValue,
not local
nValue
return 0;
}//local nValue is
destroyed.
15. However,having local
variables with the sme
name as global variables is
usually a recipe for
trouble,and should be
avoided whenever
possible.
16. New programmers ae often
tempted to use lots of
global variables,because
they are easy to work
with,especially when many
functions are involved.