Variables
Variables can be either local or global. Local variables are declared within a code block, are unknown outside and get destroyed
upon block exit. In the program below
i is a local variable.
j is a global variable.
int j;
int main()
{
int i;
}
Global variables are declared outside any functions and are accessible by all functions. If not initialized they default to 0, while local un-initialized variables have no default value. A global and local variable can have the same name, as you can see below.
int i = 5; // global
int main()
{
int i;
i = 4; // local
cout << i << " " << ::i << "\n\n";
}
In the code snippet above, the statement
i = 4; assigns 4 to the local version of
i.
In case one wants to access the global
i from within a block where a local
i is declared, the scope resolution operator can be used. The statement below prints out the
local
i first and then the global
i:
cout << i << " " << ::i << "\n\n";
Finally, a function can declare variables to obtain values at the moment the function is called. Such variables are called formal
parameters and are listed after the function’s name within parentheses. In the function below,
x is a formal parameter and it is used within the function’s body as if it were a local variable:
void printSquareAndCube(int x) // x is a formal parameter
{
cout << x * x << " " << x * x * x;
}
Local variables and formal parameters are created on the stack.
Example
#include <iostream>
using namespace std;
int i = 5; // global
int j; // initialized to 0
void printSquareAndCube(int x) // x is a formal parameter
{
cout << x * x << " " << x * x * x;
}
int main()
{
int i; // local variable. uninitialized
i = 4;
cout << i << " " << ::i << "\n\n";
printSquareAndCube(i);
cout << "\n\n";
printSquareAndCube(::i);
cout << "\n\n";
cout << "j's value: " << j;
}
Output
4 5
16 64
25 125
j's value: 0