What does 'const static' mean in C and C++?

c, c++

Solution

It has uses in both C and C++.

As you guessed, the `static` part limits its scope to that compilation unit. It also provides for static initialization. `const` just tells the compiler to not let anybody modify it. This variable is either put in the data or bss segment depending on the architecture, and might be in memory marked read-only.

All that is how C treats these variables (or how C++ treats namespace variables). In C++, a member marked `static` is shared by all instances of a given class. Whether it's private or not doesn't affect the fact that one variable is shared by multiple instances. Having `const` on there will warn you if any code would try to modify that.

If it was strictly private, then each instance of the class would get its own version (optimizer notwithstanding).

Problem

``` const static int foo = 42; ``` I saw this in some code here on StackOverflow and I couldn't figure out what it does. Then I saw some confused answers on other forums. My best guess is that it's used in C to hide the constant `foo` from other modules. Is this correct? If so, why would anyone use it in a C++ context where you can just make it `private`?

Original source

Related problems