Operator ::

Hello guys. What is tne function of this operator ::(line 25)?
What is function of that operator?


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
#include <iostream>

using namespace std;

void t1();   // function prototype
void t2();   // function prototype

int y = 2;       // global variable

int main()
{
   t1();
   t2();
 
system ("Pause");
return 0;

}

void t1()
{
     int x = 1;   // local variable  
	 int y=8;
     cout <<"in t1 x is "<< x << endl;
     cout <<"in t1 y is "<< ::y << endl;
     x++;
     y++;
}

void t2()
{
     int x = 1; // local variable  
	 int y=8;
     cout <<"in t2 x is "<< x << endl;
     cout <<"in t2 y is "<< y << endl;
}

   


Output
1
2
3
4
5
in t1 x is 1
in t1 y is 2

in t2 x is 1
in t2 y is 8
:: is a scoping operator. ::y is the global y variable defined at line 8. If you omitted it then the code would print the value of the local variable y defined at line 23.
Thanks dhayden.
:: operator is for calling the global variable.

1
2
3
4
5
6
int y = 2; //global variable 
int main() {
int y = 5; local variable
cout << ::y; /* it will call y in global scope which is 2 instead of y in local scope*/

}
Last edited on
Oh. I see now. Whenever we declared in the local but by putting :: will be refer to global.
Thanks Lorence30
Topic archived. No new replies allowed.