tags:

views:

130

answers:

1

In C++ specifically, what are the semantic differences between for example:

static const int x = 0 ;

and

const int x = 0 ;

for both static as a linkage and a storage class specifier (i.e. inside and outside a function).

+10  A: 

At file scope, no difference in C++. const makes internal linkage the default, and all global variables have static lifetime. But the first variant has the same behavior in C, so that may be a good reason to use it.

Within a function, the second version can be computed from parameters, in C or C++ it doesn't have to be a compile-time constant like some other languages require.

Within a class, basically the same thing as for functions, an instance const value can be computed in the ctor-initializer-list. A static const is set during startup initialization and remains unchanged for the rest of the program. (Note: the code for const members looks a little different because declaration and initialization are separated.)

Remember, in C++, const means read-only, not constant. If you have a pointer-to-const then other parts of the program may change the value while you're not looking. If the variable was defined with const, then no one can change it after initialization but initialization can still be arbitrarily complex.

Ben Voigt
Is there anything called file scope? I was just checking $3.3 and I think the closest is 'namespace scope'. Is my understanding right? The C++03 standard mentions file scope only in the Appendices
Chubsdad
Didn't use the term "namespace scope" because that kinda goes off on a tangent of how members of most namespaces have external linkage by default but members of the anonymous namespace have internal linkage. Which has nothing to do with a question about `static` except that it makes static for linkage control obsolete.
Ben Voigt
I would suggest that *file scope* is an artefact of the linker rather than the compiler, so may not get much attention in the language standard. Strictly it is probably "compilation unit scope".
Clifford
Dan
It's more "Compiler, if you see me try to modify this const thing (or give someone else permission to do so)", bark very loudly. In most context, `const` applies to a view of the variable and not the variable itself, someone else can have a non-`const` view of the same variable, and the compiler will be quite silent when they modify it.
Ben Voigt