Among them, the bss segment will be blocked by the system before the program is executed 自动清0;
static keyword:
static is often used to modify variables;
The role of static:
Extend the lifetime of a local variable:
static修饰Only , so that the original end 静态局部变量of the nearest curly braces, after the static modification, ;执行初始化1次局部变量的生命周期延长至整个程序结束
Limit scope:
1. Static modified 全局变量, can only 本源文件be accessed in, even if it extern外部声明is 不可以;
2. Static modified 函数, can only 本源文件be called in;
Variables modified by static:
It is stored in 全局数据区, 静态变量区including 全局静态变量and 局部静态变量, are 全局数据区allocating memory, when it is initialized, 自动初始化为 0;
pay attention:
1. If the static modification 局部变量is present 主函数执行之前, it has already been allocated;
2. In the function function, the local variable modified by static is 只是一个声明also called when it is called multiple times 不会重新赋值;
3. The local variables modified by static are still local variables, 作用域还是离的最近的花括号;
Test code:
#include<stdio.h>voidfunc1(){
int x =1;staticint y1 =5;
x++;
y1++;printf("x = %d\n",x);printf("y1 = %d\n",y1);}voidfunc2(){
staticint y =1;int x1 =5;
y++;
x1++;printf("y = %d\n",y);printf("x1 = %d\n",x1);}int x1 =999;staticint y1 =666;intmain(int argc,charconst*argv[]){
int x2;staticint y2;printf("x1 = %d\n",x1);printf("y1 = %d\n",y1);puts("--------------------------------");printf("x2 = %d\n",x2);printf("y2 = %d\n",y2);puts("--------------------------------");func1();puts("********************************");func1();puts("********************************");func1();puts("--------------------------------");func2();puts("********************************");func2();puts("********************************");func2();return0;}
operation result:
x1 =999
y1 =666--------------------------------
x2 =0
y2 =0--------------------------------
x =2
y1 =6********************************
x =2
y1 =7********************************
x =2
y1 =8--------------------------------
y =2
x1 =6********************************
y =3
x1 =6********************************
y =4
x1 =6
extern keyword:
Extern-modified variables or extern-modified functions are defined in other source files, that is, in a source file, if you want to use variables or functions defined in other source files, you need to use the extern keyword declaration;
Test code:
//代码1#include<stdio.h>int a =4;int b =5;intmy_mul(int x,int y){
return x * y;}