Global variable

I dont understand how the program prints global variable here in this code,it would be nice if some oné can help me with this... it is the last instruction in the code i have trouble to understand with...thanks in advance





1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
  
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;

const double R = 3;  //global constant

int x = 20; //global variable
int y = 25; //global variable

void fun(char y) // parameter y hides global var y
{
    string x = "TNCG012"; //local var x hides global var x
    int k = 3;

    cout << "In the fun's loop ..." << endl;
    for(int i = 0; i < R; i++) {
        int k = 10+i; //loop's local var k hides fun's local var k
        cout << "y = " << y << " x = " << x
             << " k = " << k << endl;
    }
    cout << endl << "Out the fun's loop ..." << endl;
    cout << "y = " << y << " x = " << x
         << " k = " << k << endl;
}


int main()
{
    int x = 100; // local var x hides global var x

    fun('a');

    cout << endl << "In the main ..." << endl;

    cout << "x = " << x << " y = " << y << endl;..........
//i understand everything until here butthis last statement
// when it Changes back to global variable? is it ::x? how?
    cout << "Global x = " << ::x << endl;


    return 0;
}

The unary :: scope resolution operator accesses the global variable instead of the local one with the same name.

http://stackoverflow.com/questions/20458720/how-to-access-a-global-variable-within-a-local-scope-in-c
Last edited on
Topic archived. No new replies allowed.