C语言static使用过程的一些疑惑
在编写嵌入式的程序时,常常遇到static去修饰函数和变量,有时候就很迷惑修饰作用,下面是一点心得记录下来:
一、修饰函数
假设我们有a.c和b.c两个文件,fun1函数在文件a.c中,那么该函数就不能够在b.c中使用,例如:
static void fun1(void)
{
static unsigned int temp = 0;
temp++;
printf("fun1 %d,fun2 %d\r\n",temp,temp2);
}
二、在函数内修饰变量
假设fun1函数在文件a.c中,static修饰变量temp,在该函数内重复调用fun1,temp的值会增加,比如将其应用在串口接收函数中,temp就可以作为接收的索引,有点类似“函数内的全局变量”。例如:
static void fun1(void)
{
static unsigned int temp = 0;
temp++;
}
三、多个函数static修饰了相同名字的变量
假设fun1,fun2函数在文件a.c中,fun1中static修饰变量temp,fun2中static修饰变量temp,那么temp会不会相互影响?答案是不会的,其作用域各自在其函数内。例如:
static void fun1(void)
{
static unsigned int temp = 0;
temp++;
}
static void fun2(void)
{
static unsigned int temp = 0;
temp++;
}
四、举一个综合例子加以说明
假设fun1,fun2函数在文件a.c中,fun1中static修饰变量temp1,fun2中static修饰变量temp1,变量的名字相同,在外部定义了全局变量并用static修饰,那么在b.c中如果也定义了temp2,并且也用static修饰,那么temp2的值互补影响,将作用域定义在文件内。例如:
static unsigned int temp2 = 0;/*修饰全局变量,作用域在整个a.c中*/
static void fun1(void)
{
static unsigned int temp1 = 0;
temp1++;
temp2++;
temp2++;
printf("fun1_temp = %d,temp2 = %d\r\n",temp1,temp2);
temp++;
}
static void fun2(void)
{
static unsigned int temp1 = 0;
temp2++;
printf("fun2_temp1 = %d,temp2 = %d\r\n",temp1,temp2);
}
int main(int argc, _TCHAR* argv[])
{
fun1();
fun2();
fun1();
fun2();
return 0;
}
输出结果如下:
fun1_temp = 1,temp2 = 2;
fun2_temp = 0,temp2 = 3;
fun1_temp = 2,temp2 = 5;
fun2_temp = 0,temp2 = 6;
五、static修饰后的变量默认初始化值为0。
—————————-以上内容是自己学习过程的一些感悟,如有错误地方请下方留言指教,谢谢。