zoukankan      html  css  js  c++  java
  • static关键字+变量的作用域和生命周期

    作用域:一个变量或者函数起作用的范围

    生命周期:一个变量什么时候被释放

    static关键字:修饰局部变量、修饰全局变量、修饰函数

    1.局部变量的作用域

    局部变量的作用域是离他最近的一个代码块,比如函数体的大括号、if for while循环体的代码块。超出这个代码块则无法访问。

     1 #include<stdio.h>
     2 int all;
     3 int main()
     4 {
     5     
     6     if(1)
     7     {        
     8         int a = 10;  //a 的作用域就是第7-9行 
     9     }
    10     printf("%d
    ",a);//无法访问a 
    11     
    12     test();
    13  } 
    14  
    15  void test()
    16  {
    17      int b = 6;         //b 的作用域就是第17-20行 
    18      printf("%d
    ",b);
    19      
    20  }

    2.全局变量的作用域

    全局变量的作用域为整个程序,如果在main.c定义了一个全局变量,如果在其他c文件使用这个全局变量则使用extern 声明即可

    3.局部变量的生命周期

    如上面程序中a的生命周期是理他最近的一个函数,main函数结束,a被释放。

    如上面程序中b的声明周期是离他最近的一个函数,test函数结束,b被释放。释放的意思就是该变量定义在栈上,函数被调用结束,则属于函数的栈被收回。

    4.全局变量的生命周期

    整个程序结束,全局变量all才会被释放

    5.函数的作用域

    整个程序所有c文件都可访问

    当使用static关键字修饰局部变量、修饰全局变量、修饰函数时,他们的作用域和生命周期恢复发生一些改变。(函数的生命周期不变,都是伴随整个程序)

     1 #include<stdio.h>
     2 static int all;//静态全局变量
     3 
     4 static void test()//静态函数
     5  {
     6      int b = 6;     
     7      printf("%d
    ",b);
     8      
     9  }
    10 int main()
    11 {
    12     
    13     if(1)
    14     {        
    15     static    int a = 10;  //静态局部变量 
    16     }
    17     printf("%d
    ",a);//无法访问a 
    18     
    19     test();
    20  } 
    21  

    1.static类型的局部变量

    作用域不变,生命周期扩大伴随整个程序

    2.static类型的全局变量

    作用域缩小为当前c文件可见。生命周期伴随整个程序

    3.static类型的函数

    作用域缩小为当前c文件

  • 相关阅读:
    A1066 Root of AVL Tree (25 分)
    A1099 Build A Binary Search Tree (30 分)
    A1043 Is It a Binary Search Tree (25 分) ——PA, 24/25, 先记录思路
    A1079; A1090; A1004:一般树遍历
    A1053 Path of Equal Weight (30 分)
    A1086 Tree Traversals Again (25 分)
    A1020 Tree Traversals (25 分)
    A1091 Acute Stroke (30 分)
    A1103 Integer Factorization (30 分)
    A1032 Sharing (25 分)
  • 原文地址:https://www.cnblogs.com/1024E/p/13216376.html
Copyright © 2011-2022 走看看