Scope. Namespaces
Scope
Scope refers to the lifetime and accessibility of a variable. How large the scope is depends on where a variable is declared. For example, if a variable is declared at the top of a class then it will accessible to all of the class methods. If it’s declared in a method then it can only be used in that method.
A pair of curly braces ({}) defines a new scope.
For example:
int Foo {
int a = 10;
}
int a = 5;
log.message("Foo::a is %d, a is %d", Foo::a,a);
// Output: Foo::a is 10, a is 5
If there is recursion, then variables will be stored in a stack.
int foo(int n) {
if(n < 2) return 1;
return foo(n - 2) + foo(n - 1);
}
int n=5;
log.message("%d\n",foo(n));
// Output: 8
Namespaces
Namespaces allow to group entities like classes, objects and functions under a name. This way the global scope can be divided in "sub-scopes", each one with its own name.
The format of namespaces is:
namespace identifier {
// entities
}
The example of namespace defining:
namespace Foo {
int a = 10;
}
int a = 5;
log.message("Foo::a is %d, a is %d", Foo::a,a);
// Output: Foo::a is 10, a is 5
It is also possible to use using keyword to introduce a name from a namespace into the current declarative region.
namespace Foo::Bar {
int a = 10;
}
void foo() {
using Foo::Bar;
log.message("Foo::Bar::a is %d\n",a);
}
foo();
// Output: Foo::Bar::a is 10