In C (unlike C ++), an arithmetic expression is a "constant expression" only if each value in the expression is a numeric constant or the name of an enumeration value. That is, although you could declare a variable as static const int , you still cannot use this (constant) variable in a constant arithmetic expression.
Note that “constant expression” is a phrase defined by a formal standard that defines the C language. There are other expressions that are intuitively constant, but they are not included in the formal definition.
A variable with "static storage duration" is simply a variable that exists at run time. Most of these variables are global variables (i.e. they are not part of any function, not even main ), but in C and C ++ you can have a static variable inside the scope of the function. Such a variable is initialized only once, and only one instance of it exists, regardless of how many times the function is called.
Global variables and other variables with a static storage duration can only be initialized with a constant expression as defined above. This is the case whether they are const variables. The problem is that the variables have a static storage duration, which means that they must be initialized before the program runs. (During program execution, there is a variable with a static storage duration, therefore, if it is initialized, that is, an initial value is specified, and a value is not assigned during program execution, initialization must be performed 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, this is not the case, so the C compiler does not need to track the initial value of the static const variables.
source share