// 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 :
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.