static_keyword

static keyword(C语言)

1. 什么是static 关键字

  1. static 关键字的定义: Static is a keyword used in C programming language. It can be used with both variables and functions, i.e., we can declare a static variable and static function as well. An ordinary variable is limited to the scope in which it is defined, while the scope of the static variable is throughout the program.(我的理解就是static既能用于函数的声明当中,也能用于函数的声明当中,而且static关键字定义的变量或者函数贯穿了整个program)。

2. static 关键字注意事项

  1. 函数内的静态变量在调用之间保持其值
#include <stdio.h>

void foo()
{
    int a = 10;
    static int sa = 10;

    a += 5;
    sa += 5;

    printf("a = %d, sa = %d\n", a, sa);
}


int main()
{
    int i;

    for (i = 0; i < 10; ++i)
        foo();
}

打印如下:

a = 15, sa = 15
a = 15, sa = 20
a = 15, sa = 25
a = 15, sa = 30
a = 15, sa = 35
a = 15, sa = 40
a = 15, sa = 45
a = 15, sa = 50
a = 15, sa = 55
a = 15, sa = 60
  1. static 关键字也可以用来修饰函数,修饰的该函数只能被用于该文件当中
    文件目录如下:
├── file1.c
├── file2.c
// file1.c 

#include <stdio.h>
#include "file2.c"
void fun(){   // there is no static keyword
    printf("hello");
}
int main(){
    fun();
    return 0;
}
//file2.c file

#include <stdio.h>
void fun(){
    printf("hello");
}
//编译运行file1.c会报错如下
//err:
//goto.c:3:7: error: redefinition of 'fun'

解决该问题的方法:可以在file2.c文件里fun()函数加上static 关键字

  1. static 关键字定义的变量如果没有被预初始化,会被初始化为0

#include <stdio.h>
int main()
{
    static int x;
    int y;
    printf("%d \n %d", x, y);
}
// 打印结果如下:
// 0 
// [some_garbage_value]

3.static can only be seen in the scope it’s declared.

#include <stdio.h>
int main(){
     {
           static int a=2;
     }
    printf("%d",a);
    return 0;
}
//这段代码运行之后会报错,请勿这样使用static关键字!!!
//static.c: In function 'main':
//static.c:6:17: error: 'a' undeclared (first use in this function)
//   6 |     printf("%d",a);
//      |                 ^
// static.c:6:17: note: each undeclared identifier is reported only once for each function it appears in

总结:不管是static修饰的变量也好,还是函数也好。只能作用在其作用域,而且static修饰的变量在其作用域当中不会随着栈帧的移动而发生变化,贯穿整个program。变量的释放不会随着作用域的结束而被释放,而是随着整个main函数结束而释放

以上就是我对static的理解,这是博主第一个帖子,希望能帮助到大家!

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值