static keyword useless in namespace scope?

20,086

Solution 1

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.

Solution 2

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.

Solution 3

C++ Standard §7.3.1.1/2:

The use of the static keyword is deprecated when declaring objects in a namespace scope (see annex D); the unnamed-namespace provides a superior alternative.

Unless the unnamed namespace provides a superior alternative in the future Standard it will be undeprecated to achieve C compatibility.

Share:
20,086
Admin
Author by

Admin

Updated on July 15, 2022

Comments

  • Admin
    Admin almost 2 years
    namespace N
    {
       static int x = 5;
    }
    

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