scdmb
scdmb

Reputation: 15631

Is a namespace the same thing as scope in C++?

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

Answers (4)

Marcelo Cantos
Marcelo Cantos

Reputation: 186068

No. A namespace is a kind of scope, but there are several kinds of scope that aren't namespaces. Some examples are:

  • block scope: symbols (usually local variables) declared within a statement block enclosed in {...};
  • function scope: a function's outermost block scope;
  • class scope: the members of a class.

Upvotes: 10

Matthieu M.
Matthieu M.

Reputation: 300209

Not completely.

In C++, a scope is generally determined by pair of opening and closing braces: { and }, this includes:

  • namespaces
  • classes and structs
  • functions and methods
  • simple "blocks" within functions or methods

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

Wikipedia's articles on Scope & Variables should be helpful.

Upvotes: 0

Luchian Grigore
Luchian Grigore

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

Related Questions