常用关键字static用法01

不太常用会遗忘,通过比较来加深印象和理解

1.静态变量不能跨函数使用:

#include <stdio.h>

void f(int q)
{ q=10;
//return 0;
}
void g(int * p)
{
*p=11;
}
int main(void)
{
int i,j;
f(i);
g(&j);
   printf("i=%d\n",i);
    printf("i=%d\n",j);
return 0;

}

编译结果:

i=0
i=11
--------------------------------
Process exited after 0.1025 seconds with return value 0

请按任意键继续. . .

2.静态局部变量

//1.在{}内部定义的变量就是局部变量
//2.static局部变量,是在编译阶段就已经分配空间,函数没有调用前,它已经存在了 
//3.当离开{},static局部变量不会释放,只有程序结束,static变量才会释放
//4.局部变量的作用域在当前的{},离开此{},无法使用此变量
//5.{}的普通局部变量,加不加auto关键字等价,普通局部变量也自动变量?

//6.不同的{】中,变量名字可以一样,可以把{}类比房子,不同房子可以有同名的小伙伴 

扫描二维码关注公众号,回复: 2686565 查看本文章

#include <stdio.h>

int static_fun()

{
    static int i=0;
   i++;
      printf("static_fun i = %d\n",i);


int fun()
{
    int i=0;
     i++;
      printf("static_fun i = %d\n",i);


int main(void)
{
static_fun(); 
static_fun(); 
static_fun(); 
    fun(); 
    fun(); 
    fun(); 
return 0;
}

static_fun i = 1
static_fun i = 2
static_fun i = 3
static_fun i = 1
static_fun i = 1
static_fun i = 1
--------------------------------
Process exited after 0.1867 seconds with return value 0

请按任意键继续. . .


                                            from:代码例子来自传智播客(如有侵权,联系删)

猜你喜欢

转载自blog.csdn.net/qq_40025335/article/details/79699276