When I run this piece of code:
void main(){
int a = 5;
static int i = a+5;
printf("%d", i);
}
I get the error: in开发者_开发问答itializer element is not constant
What does this mean?
Static variables in function scope go in data segment. Data segment is initialized at compile time. That means the initial value has to be known at compile time. In your case, the initial value (value of a) comes from a variable on stack which is available only at runtime.
In C Initializer should be some constant. however you can do something like this...
int a = 5;
static int i;
i = a + 5;
printf("%d", i);
this will not generate any error...
You can not assign a variable to a static.
since you initialize the variable i
not with a constant number (like int a = 5;
) but with an expression (a+5
) which is illegal.
The keyword static
mean that there will be exactly one instance of the variable i
, and that instance will live throughout the life of the program. This is useful, for example, if you want to store values between function calls.
As the variable is initialized when the application is started, the value must be constant.
In your case, there is no need to declare the "static", as it will get a new value every time the function is called.
精彩评论