Reputation: 15631
Is a namespace the same thing as scope in C++ programming language? Are these two words synonyms and can be used interchangably?
Upvotes: 2
Views: 253
Reputation: 186068
No. A namespace is a kind of scope, but there are several kinds of scope that aren't namespaces. Some examples are:
{...}
;Upvotes: 10
Reputation: 300209
Not completely.
In C++, a scope is generally determined by pair of opening and closing braces: {
and }
, this includes:
However there are a few exceptions, or specificities for a number of statements that may introduce variables that will live in the scope they immediately precede:
for (int i = 0; i < 10; ++i) {
// i accessible here
}
while (int c = getchar()) {
// c accessible here
}
try {
// ...
} catch(std::exception const& e) {
// e accessible here
}
void foo(int i) {
// i accessible here
}
And there is the most surprising if
statement:
if (int var = /**/)
{
// var is accessible here
}
else
{
// var is accessible here too!
}
Those scopes are a bit special :)
They also can degenerate in implicit scopes, because the C rules (that C++ also follows) make the {
and }
pair optional for the statements:
for (int i = 0; i < 10; ++i) std::cout << i << "\n";
// i no longer accessible here
There is also a scope for the template parameters: they are brought to life at their declaration point and live until the end of the class or function they were templating.
template <typename U>
void foo() {
} // U accessible up until this point
Finally, there is also the "most outer" scope, that is the global namespace, which is the "root" scope, in a way.
Upvotes: 2
Reputation: 1
Wikipedia's articles on Scope & Variables should be helpful.
Upvotes: 0
Reputation: 258638
No they are not.
A scope is pretty much similar to an object's lifetime - similar, not the same.
class A;
//....
{
A a; //begin scope for object a
}
//object a is out of scope
A namespace is a useful way to group declarations and definitions in C++.
You can name a namespace a scope, but a scope is much more than that. See the scope resolution operator: a method or variable can be part of a class scope and not in a namespace.
Upvotes: 0