Local and Global Variables

Local Variables

All the variables we have used thus far have been local variables.  A local variable is a variable which is either a variable declared within the function or is an argument passed to a function.  As you may have encountered in your programming, if we declare variables in a function then we can only use them within that function.  This is a direct result of placing our declaration statements inside functions.

Consider a program that calls a swap() function.

#include <iostream.h>

void swap(int x, int y) {
  int temp = x;
  x = y;
  y = temp;
}

int main()
{
  int A, B;

  cin >> A >> B;

  cout << "A: " << A << "." << endl;
  cout << "B: " << B << "." << endl;
  swap(A, B);
  cout << "A: " << A << "." << endl;
  cout << "B: " << B << "." << endl;

  return 0;
}

Consider variables which are in scope (DEF: portion of a program in which a
variable is legally accessible) in the main() and swap() functions:
 
Function
Accessible variables
main
A, B
swap
temp, x, y

If you attempted to use A was in swap(), a compilation error would result ("undeclared identifier") since it is a local variable in only main().
 

Global Variables

A global variable (DEF) is a variable which is accessible in multiple scopes.  It is important to note that global variables are only accessible after they have been declared.  That is, you can use a variable is is declared below its usage in the text.  For instance, if we consider this simple program, we have one global variable, w.

#include <iostream.h>

double w;

void Z() {
  w = 0;
  return;
}

void Q() {
  int index;

  w = 2;
  return;
}

int main() {
  int i;

  w = 4;

  return 0;
}

w is a global variable which is in scope in all three functions in this program: Z(), Q(), and main().  This program also has local variables: index is local to Q(), and i is local to main().

Scoping can viewed easily in the following table.
 
 
Function
Accessible Variables
main
w, i
Z
w
Q
w, index

Another example.

#include <iostream.h>

int sum;

void Z(int alpha) {
  sum += 1;
  alpha *= 3;

  return;
}

double total;

void Q() {
  int index;

  total = index;

  return;
}

int main() {
  int i;
  int w = 10;

  sum = 0;
  total = 0;

  return 0;
}

We construct the scoping table.
 
Function
Accessible Variables
main
sum total, i, w
Q
sum, total, index
Z
sum, alpha

Note that since the variable total is declared below Z() in the text, total is not in scope in Z().
 
 

WARNING

Global variables are not generally used.  It is a contradiction of modularity to have variables be accessible in functions in which they are not used.  In the previous example, sum is not used in Q() even though it is in scope.  If there is a situation where one can justify using a global variable, then it is acceptable.