Introduction
Imagine you have many boxes inside each other, and you want to find a specific item. The problem is knowing which box to look in first. Scope resolution solves this by telling us exactly where to find a name or variable in a program.
Imagine you live in a big apartment building with many rooms. If you want to find your friend’s phone number, you first check your own room’s address book. If it’s not there, you check the building’s main directory. This way, you know exactly where to look.
┌───────────────┐
│ Global │
│ Scope │
│ (Building) │
└──────┬────────┘
│
┌──────▼───────┐
│ Function │
│ Scope │
│ (Room) │
└─────────────┘:: operator in scope resolution?:: operator is used to access variables or functions that belong to a specific scope, especially when multiple scopes have the same name.:::: means 'from this scope' [OK]:: with assignment operatorx inside a function when a local variable with the same name exists?:: placed before the variable name to access the global variable.::x to access the global variable x inside a function where a local x exists.::x [OK]:: before variable for global access [OK]int x = 10;
void func() {
int x = 20;
print(::x);
}func() is called?xx with value 10 and a local x inside func() with value 20.::x usage in print(::x)::x accesses the global x, ignoring the local one.int x = 5;
void func() {
int x = 10;
print(x::);
}:: must precede the variable or function name, not follow it.print(x::);x:: is invalid syntax; it should be ::x to access global scope or just x for local.:: after variable namenamespace Outer {
int value = 100;
namespace Inner {
int value = 200;
int getValue() {
return Outer::value + value;
}
}
}Outer::Inner::getValue() return?Outer::value is 100, and Inner::value is 200.getValue()Outer::value + value, where value refers to Inner::value. So, 100 + 200 = 300.Pass the test and this pattern moves unknown