C++ semantics of `static const` vs `const`

c++

Solution

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 `static` 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.

Problem

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).

Original source

Related problems