Use of Unary Scope Operator means use of double colon symbol to access something that is not immediately reachable from main() section of our programs.
For example, we have two variables temp here with same name. Values in those variables are different.
If we use just temp in main() section, we will have 20 as result.
But to access temp outside main() section, we will use same name of variable but with double colons as prefix. In this case value of an external temp is 50:
#include <iostream>
#include <cstdlib>
using namespace std;
int temp = 50;
int main() {
int temp = 20;
cout << "Outside Temp Value: " << ::temp << endl;
cout << "Inside Temp Value: " << temp << endl;
return 0;
}
Result:
Outside Temp Value: 50
Inside Temp Value: 20
Process returned 0 (0x0) execution time : 0.062 s
Press any key to continue.
This is interesting situation when we have three temp variables. One is external, one is internal in main() section, and one is internal in printTemp() function.
All of them have same name, but they are used in different ways:
#include <iostream>
#include <cstdlib>
using namespace std;
int temp = 50;
void printTemp() {
int temp = 10000;
cout << "In Function Temp Value: " << temp << endl;
}
int main() {
int temp = 20;
cout << "Inside Temp Value: " << temp << endl;
cout << "With Unary Scope Temp Value: " << ::temp << endl;
printTemp();
return 0;
}
Result:
Inside Temp Value: 20
With Unary Scope Temp Value: 50
In Function Temp Value: 10000
Process returned 0 (0x0) execution time : 0.161 s
Press any key to continue.
No comments:
Post a Comment