zoukankan      html  css  js  c++  java
  • 【学习笔记】【C语言】static和extern对变量的作用

     1.全局变量分2种:
     外部变量:定义的变量能被本文件和其他文件访问
     1> 默认情况下,所有的全局变量都是外部变量
     1> 不同文件中的同名外部变量,都代表着同一个变量
     
     内部变量:定义的变量只能被本文件访问,不能被其他文件访问
     1> 不同文件中的同名内部变量,互不影响
     
     static对变量的作用:
     定义一个内部变量
     
     extern对变量的作用:
     声明一个外部变量
     
     static对函数的作用:
     定义和声明一个内部函数
     
     extern对函数的作用:
     定义和声明一个外部函数(可以省略)

    2.代码

    main.c

     1 #include <stdio.h>
     2 
     3 void test();
     4 
     5 // 定义一个外部变量
     6 
     7 //int a; 这么多个a都是代表同一个a
     8 //int a;
     9 //int a;
    10 //int a;
    11 //int a;
    12 
    13 
    14 // 定义一个内部变量
    15 static int b;
    16 
    17 // 声明一个外部变量
    18 //extern int a;
    19 
    20 int main()
    21 {
    22     //b = 10;
    23     
    24     //test();
    25     
    26     extern int a;
    27     a = 10;
    28     
    29     /*
    30     a = 10;
    31     
    32     test();
    33     
    34     printf("a的值是%d
    ", a);*/
    35     
    36     return 0;
    37 }
    38 
    39 
    40 int a;

    one.c

     1 #include <stdio.h>
     2 
     3 int a;
     4 
     5 static int b;
     6 
     7 void test()
     8 {
     9     printf("b的值是%d
    ", b);
    10     
    11     /*
    12     printf("a的值是%d
    ", a);
    13     
    14     a = 20;*/
    15 }

    static与局部变量

     1 #include <stdio.h>
     2 
     3 /*
     4  static修饰局部变量的使用场合:
     5  1.如果某个函数的调用频率特别高
     6  2.这个函数内部的某个变量值是固定不变的
     7  */
     8 
     9 void test()
    10 {
    11     static double pi = 3.14;
    12     
    13     double zc = 2 * pi * 10;
    14     
    15     int a = 0;
    16     a++;
    17     printf("a的值是%d
    ", a); // 1
    18     
    19     /*
    20      static修饰局部变量:
    21      1> 延长局部变量的生命周期:程序结束的时候,局部变量才会被销毁
    22      2> 并没有改变局部变量的作用域
    23      3> 所有的test函数都共享着一个变量b
    24      */
    25     static int b = 0;
    26     b++;
    27     printf("b的值是%d
    ", b); // 3
    28 }
    29 
    30 int main()
    31 {
    32     for (int i = 0; i<100; i++) {
    33         test();
    34     }
    35     
    36     
    37     test();
    38     
    39     test();
    40     
    41     test();
    42     
    43     
    44     return 0;
    45 }
     
  • 相关阅读:
    Git Bash 常用指令
    C/C++连接MySQL数据库执行查询
    question from asktom
    ORACLE AWR报告
    查看oracle表索引
    ORACLE数据库关闭与启动
    SYS vs SYSTEM and SYSDBA vs SYSOPER
    【面试】二叉树遍历的非递归实现
    快速排序的非递归实现
    MySQL数据库基础
  • 原文地址:https://www.cnblogs.com/dssf/p/4622774.html
Copyright © 2011-2022 走看看