global vs. local variables

if i declare global variables a, b and c.
then in main i declare local variables c and d.
then i have a function that uses the parameters c and d.
do c and d use the local variable from main? or does c pull from the global?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
int a;
int b;
int c;

void main()
{
int c;
int d;

}

void function(int c, int d)
{
int b;
int e;

}
do c and d use the local variable from main? or does c pull from the global?


Neither.

Every time you say int a; you are creating a new variable. Just because that variable shares a name with another variable doesn't mean they are the same variable.

Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
int a = 0;  // the global a

void changea()
{
  a = 5;  // changes the global a
}

int main()
{
  cout << a;  // prints the global a (0)
  {
    int a = 1; // the local a

    cout << a;  // prints the local a (1)

    changea();  // change the global a

    cout << a;  // prints the local a (still 1, hasn't been changed)
  } // local a goes out of scope here -- it no longer exists
  cout << a;  // since the local a no longer exists, this prints global a (5)
}



Parameters work the same way:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int c = 0;

void function(int c)
{
  cout << c;  // prints the local (parameter) c, not the global one
}

int main()
{
  int b = 3;  // main's local b = 3
  int c = 2;  // main's local c = 2
  // global c remains unchanged at 0

  function( b );  // passes b to function.
   // this assigns function's c to b (3).  So this will print 3
}


Note that all 3 'c's here are different. There's a global c, main's c, and function's c.
You need to call the function, otherwise all you have is a function declaration that never gets run:
1
2
3
4
5
6
7
8
9
10
11
void function(...)
{
... //Declare the function before you use it
}

void main()
{
int c = 9;
int d = 0;
function(c,d); //Pass arguments to the function
}

In this case the local variables of main will hide the global variables. I believe to access the global ones just prepend the scope operator to your variables ('::'):
 
function(::c,::d);
ah yes, Disch. thank you. i remember that now.

and thanks BlackSheep.
Topic archived. No new replies allowed.