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).
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
At file scope, no difference in C++.
constmakes 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
constvalue can be computed in the ctor-initializer-list. Astatic constis set during startup initialization and remains unchanged for the rest of the program. (Note: the code forstaticmembers looks a little different because declaration and initialization are separated.)Remember, in C++,
constmeans read-only, not constant. If you have a pointer-to-constthen other parts of the program may change the value while you’re not looking. If the variable was defined withconst, then no one can change it after initialization but initialization can still be arbitrarily complex.