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
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).
A lot of people gave the basic answer but nobody pointed out that in C++
const defaults to
namespace level (and some gave wrong information). See the C++98 standard section 3.5.3.
First some background:
Translation unit: A source file after the pre-processor (recursively) included all its include files.
Static linkage: A symbol is only available within its translation unit.
External linkage: A symbol is available from other translation units.
This includes the global namespace aka global variables.
static const int sci = 0; // sci is explicitly static const int ci = 1; // ci is implicitly static extern const int eci = 2; // eci is explicitly extern extern int ei = 3; // ei is explicitly extern int i = 4; // i is implicitly extern static int si = 5; // si is explicitly static
static means the value is maintained between function calls.
The semantics of function
static variables is similar to global variables in that they reside in the program's data-segment (and not the stack or the heap), see this question for more details about
static variables' lifetime.
static means the value is shared between all instances of the class and
const means it doesn't change.