The role of static keyword in C language

Brief introduction of the function of static keyword in C language

—Static keyword, as a relatively common and important keyword, plays a great role in program modularization. The role in C language is mainly divided into:

variable

(1). When modifying local variables:
a. The life cycle of a static modified local variable becomes a global attribute, which is equivalent toChanged the life cycle of local variables, Do not change the scope (this code block).
b. The variable definition modified by static will take it even if it is not assignedInitialize to 0 value. It is initialized only on the first call.
c. The storage location will not be stored on the stack, placedData segment

(2). When modifying a global variable:
a. Change the link attribute of the variable to make the variableCan only be accessed in this file, Which is equivalent to changing the scope. Other files can define the same type name as the modified variable without conflicting with each other.

function

Modified local variables and functions are the same in many places.
(3). When modifying the function:
a. Change the link attribute of the function to make the function file scope, that is, it can only be used in the current file and cannot be used by other files.
b. In subsequent calls, the variable uses the value saved after the previous function call is completed.

Other considerations:
The value of static modified variables can be changed. It does not limit the value of the variable, but only changes in the scope or life cycle. The const modified variable cannot be changed its value.

Use the following simple example to illustrate the role of static:
1. Function

void Abc(){
    
    //定义一个自定义函数用来做样例
int i=0;  //循环一次就会初始化一次,所以会一直打印初始化后i++的值,也就是1
i++;
printf("i= %d\n",i);
}
int main(){
    
    
for(int i=0;i<10;i++){
    
    
Abc();
}
return 0;
}

The results are as follows:

Insert picture description here

void Abc(){
    
    
  static int i=0;//使用static修饰变量,使得初始化只进行一次
i++;
printf("i= %d\n",i);
}
int main(){
    
    
for(int i=0;i<10;i++){
    
    
Abc();
}
return 0;
}

The results are as follows:
Insert picture description here
2. In the case of global variables, the first type can be called; the
second type can not be called with static added The
first type: the
Insert picture description here
Insert picture description here
second type
Insert picture description here
Insert picture description here
Insert picture description here

Guess you like

Origin blog.csdn.net/zhaocx111222333/article/details/109158938