In C (unlike C++), an arithmetic expression is a "constant expression" only if every value in the expression is a numeric constant or the name of an enumeration value. That is, although you might have declared a variable to be a static const int
, you still cannot use that (constant) variable in a constant arithmetic expression.
Note that "constant expression" is a phrase defined by the formal standard which defines the C language. There are other expressions which are intuitively constant, but they are not included in the formal definition.
A variable with "static storage duration" is simply a variable which exists throughout the execution of the program. Most such variables are global variables (i.e. not part of any function, not even main
), but in C and C++ you can have a static
variable inside the scope of a function. Such a variable is initialized only once, and only a single instance of it exists regardless of how many times the function is called.
Global variables, and other variables with static storage duration, can only be initialized to a constant expression as per the above definition. This is the case whether or not they are const
variables. The issue is simply that the variables have static storage duration, which means that they must be initialized before the program executes. (A variable with static storage duration exists throughout the execution of the program, so if it is initialized -- that is, given an initial value, as opposed to being assigned a value during the program's execution -- the initialization must occur before the program executes.)
In C++, a variable declared static const
is considered a constant value, so it can appear in constant expressions. In C, however, that is not the case, so a C compiler does not need to track the initial value of static const
variables.