Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static keyword useless in namespace scope?

Tags:

namespace N {    static int x = 5; } 

What could be the importance/use-cases of declaring having a static variable at namespace scope?

like image 968
User29729 Avatar asked May 17 '11 17:05

User29729


People also ask

Are namespaces static?

Unnamed Namespaces Also see Static Variables. All declarations can be given internal linkage by placing them in unnamed namespaces, and functions and variables can be given internal linkage by declaring them static . This means that anything you're declaring can not be accessed from another file.

Are variables in namespace static?

When you declare a variable as static , it means that its scope is limited to the given translation unit only. Without static the scope is global. When you declare a variable as static inside a . h file (within or without namespace ; doesn't matter), and include that header file in various .

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.

What is the scope of using namespace?

A namespace is a declarative region that provides a scope to the identifiers (the names of types, functions, variables, etc) inside it. Namespaces are used to organize code into logical groups and to prevent name collisions that can occur especially when your code base includes multiple libraries.


2 Answers

static variable at namespace scope (global or otherwise) has internal linkage. That means, it cannot be accessed from other translation units. It is internal to the translation unit in which it is declared.

like image 149
Nawaz Avatar answered Nov 04 '22 01:11

Nawaz


Annex D (Compatibility features) [C++03]

D2: The use of the static keyword is deprecated when declaring objects in namespace scope.

Use unnamed namespaces instead as mentioned in this post.

static keyword imparts internal linkage to variables/objects in C as well as in C++ in namespace scope as others have mentioned in their posts.

P.S: Thie feature has been undeprecated as per the latest draft (n3290). In n3225 §7.3.1.1/2 is present but striked out.

like image 25
Prasoon Saurav Avatar answered Nov 04 '22 00:11

Prasoon Saurav