Scope operator changing.

Why is it that in the second cout stmt of the main function, ::abc is printed out as 11? Doesn't :: refer back to the global variable which in this case is 10?
Is this the correct understanding? Please correct me if I'm wrong.

Also, in the function fn, ::abc = abc; changes the global variable as well? So functions can change global variables? Is this the correct understanding?

Newbie to programming, thanks!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
using namespace std;

int abc = 10;

int fn (int abc)
{
    abc++;
    ::abc = abc;
    return abc;
}
int main()
{
    cout << abc << endl;
    abc++;
    int abc = 5;
    cout << abc << endl << ::abc << endl;
    cout << fn(abc+2) << endl;
    cout << ::abc << endl;
    return 0;
}
Last edited on
Why is it that in the second cout stmt of the main function, ::abc is printed out as 11? Doesn't :: refer back to the global variable which in this case is 10?


The global variable abc is 11 it is incremented on line 15.
Oh, ok! I thought that the variable abc was incremented only in the main function and global was unchanged.

But now I see, that main has been manipulating the global variable UNTIL we officially declared int abc = 5 on line 16. Hopefully this is the right reasoning. If not please correct.

Thanks for clarifying.
But now I see, that main has been manipulating the global variable UNTIL we officially declared int abc = 5 on line 16.

correct
Last edited on
Topic archived. No new replies allowed.