美文网首页十天学会C语言程序员
C语言day10-03static对局部变量-作用

C语言day10-03static对局部变量-作用

作者: liyuhong165 | 来源:发表于2016-05-08 16:23 被阅读39次

    pragma mark static对局部变量-作用

    pragma mark 概念

    /**
     static int b = 0;   // 原本在栈里面 通过static修饰之后 到了静态区
     static  是会开辟一次存储空间
     */
    

    pragma mark 代码

    #include <stdio.h>
    void test()
    {
        int a = 0;  // 局部变量 放在栈
        // 当使用static 来修饰局部变量,那么会延长局部变量的声明周期,并且会更改局部变量存储的位置,将局部变量从栈转移到静态区中
        static int b = 0;   // 原本在栈里面 通过static修饰之后 到了静态区
        // 只要使用static修饰局部变量后,当执行到定义局部变量的代码就会分配存储空间,但是只有程序结束才会释放该存储空间
        a++;
        b++;
        printf("a = %i\n",a);   // 1
        printf("b = %i\n",b);   // 2
        printf("----------\n");
    
    }
    void demo(int r)
    {
        /*
         应用场景:
         当某个方法的调用 频率非常高,而该方法中更有些变量的值是固定不变的
         那么这个是会 就可以使用static来修饰该变量,让该变量只开辟一次存储空间 
         这样可以提高程序的效率和性能
         */
        double pi = 3.1415926 ;  // 固定
        double  res = pi * r * r;
        printf("res = %lf\b",res);
    }
    int main()
    {
        test();
        test();
        
        for (int i = 0; i < 100; i++) {
            demo(i);
        }
        return 0;
    }
    
    
    

    相关文章

      网友评论

        本文标题:C语言day10-03static对局部变量-作用

        本文链接:https://www.haomeiwen.com/subject/cnwjrttx.html