Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Namespace without a name in C++ [duplicate]

Tags:

c++

namespaces

Possible Duplicate:
Unnamed/anonymous namespaces vs. static functions

I came across this code

namespace ABC { namespace DEF {  namespace { 

I expected the namespace should be followed by some name, but it's not the case with this code.

Is this allowed in C++? What's the advantage for this unnamed namespace?

like image 686
prosseek Avatar asked Mar 08 '11 22:03

prosseek


People also ask

What is an unnamed namespace?

Unnamed NamespacesThey are directly usable in the same program and are used for declaring unique identifiers. In unnamed namespaces, name of the namespace in not mentioned in the declaration of namespace. The name of the namespace is uniquely generated by the compiler.

What is the point of anonymous namespace?

An anonymous namespace makes the enclosed variables, functions, classes, etc. available only inside that file. In your example it's a way to avoid global variables. There is no runtime or compile time performance difference.

Why there is no namespace in C?

Namespace is a feature added in C++ and is not present in C. A namespace is a declarative region that provides a scope to the identifiers (names of functions, variables or other user-defined data types) inside it. Multiple namespace blocks with the same name are allowed.

Why is an unnamed namespace used instead of static?

1.1 Unnamed namespaces, paragraph 2: The use of the static keyword is deprecated when declaring objects in a namespace scope, the unnamed-namespace provides a superior alternative. Static only applies to names of objects, functions, and anonymous unions, not to type declarations.


1 Answers

It's called an unnamed namespace / anonymous namespace. It's use is to make functions/objects/etc accessible only within that file. It's almost the same as static in C.

like image 51
Marlon Avatar answered Sep 22 '22 15:09

Marlon