Use the Global or the Local?

// file : scope.C
#include <iostream.h>
 
// these are global variables
int junk, car, fin;
 
void bar(int fin)
{
  int j;
 
  car = 32;  j = 10;  fin = fin + 12;
  cout << "IN BAR :\n";
  cout << "car is " << car;
  cout << ", j is " << j;
  cout << ", fin is " << fin << endl << endl;
}
 
int main()
{
  int j, foo, car;
 
  fin = 10;  j = 20;  foo = 30;  junk = 40;  car = 66;
  cout << "IN MAIN\n";
  cout << "fin is " << fin;
  cout << "j is " << j;
  cout << ", foo is " << foo;
  cout << ", junk is " << junk;
  cout << ", car is " << car << endl << endl;
  bar(j);
  cout << "IN MAIN\n";
  cout << "fin is " << fin;
  cout << "j is " << j;
  cout << ", foo is " << foo;
  cout << ", junk is " << junk;
  cout << ", car is " << car << endl << endl;

  return 0;
}

Here are the rules (the scope rules) we use to determine which variable we are referring to :

  1. Refer to a local variable if there is one.
  2. If there is no local variable, refer to the global one.
  3. If there is no local variable and there is no gloabl variable, then there's an error. Never try to refer to a variable in the calling function (``main'' in most cases).

Kind of confusing, huh? This is why die-hard computer programers frown upon using globals. Ever.

For future reference, a good quiz question could give you a program like the one above and ask you to figure out what it prints.