局部静态变量是一个变量,其生存期不会随着声明它的函数调用而停止。它一直延伸到完整程序的生命周期。所有函数调用共享本地静态变量的同一副本。
这些变量用于计算函数被调用的次数。静态变量的默认值为 0。而普通局部作用域指定在块中定义的变量仅在该块中可见,而在块外不可见。
块之外的全局变量在程序结束时是可见的。
例
以下是局部变量的 C 程序
#include<stdio.h>
main ( ){
int a=40 ,b=30,sum; //local variables life is within the block
printf ("sum=%d" ,a+b);
}
输出
当上述程序被执行时,它会产生以下输出
sum=70
例
以下是全局变量的 C 程序
int c= 30; /* global area */
main ( ){
int a = 10; //local area
printf ("a=%d, c=%d", a,c);
fun ( );
}
fun ( ){
printf ("c=%d",c);
}
输出
当上述程序被执行时,它会产生以下输出
a =10, c = 30
例
以下是局部静态变量的 C 程序
#include <stdio.h>
void fun(){
static int x; //default value of static variable is 0
printf("%d ", a);
a = a + 1;
}
int main(){
fun(); //local static variable whose lifetime doesn’t stop with a function
call, where it is declared.
fun();
return 0;
}
输出
当上述程序被执行时,它会产生以下输出
0 1