Variables (local, global)???
There are three places where a variable can be declared : local, formal parameters and local.
Local Variables :
Variables
declared within a function are called local variables. They are also sometimes
called automatic variables. These variables can be used only within the block
(or function) in which they are declared. A block starts with an opening curly
brace and ends in a closing curly brace. A local variable is created upon entry
into the block and destroyed when the program exits that block.
For example :
void test ( )
{
// Start of block
int q;
q = 2;
}
// End of block
void test2 (
)
// Start of another block
{
int q;
q = 5;
}
The two q's that I have declared in the two
functions (test and test2)
have no relationship with each other. Each q is
known only within its own block (since it is a local variable).
The main advantage is that a local variable cannot be accidentally altered from
outside the block.
Formal
Parameters :
As we have seen, if a function is to use arguments then it must declare
variables that will accept values of the arguments. These variables are called
formal parameters. For example :
int remainder (int a, int
b)
// In the function remainder, the parameters are a
and b.
{
return a % b;
}
Global
Variables :
These variables are known throughout the program. They can be used by any part
of the program and are not limited like local variables. They are declared
outside the main function.
#include <iostream>
using namespace std;
int
count;
// count is a global variable
int main ( )
{
......
}
Global variables will take up more memory because
the compiler has to always keep it in memory.
Avoid using too many global variables. Use it only if the variable is going to
be used by a number of functions.
The next section is on : Arrays
Or go back to the Contents.
Copyright © 2002 Sethu Subramanian All rights reserved.