zoukankan      html  css  js  c++  java
  • C语言-第2课

    第2课 - auto,register,static分析 

    1. auto关键字

    l C 言中的 量可以有自己的属性。

    在定义变量的候可以加上“属性”关键字。

    l “属性”关键字指明变量的特有意义。

    autoC 言中局部变量的默认属性,编译器默认所有的局部变量都是auto的。

    1. static关键字

    l static关键字指明变量的“静态”属性。

    l static关键字同时具有“作用域限定符”的意义。

    static修饰的局部变量存储在程序静态区,static的另一个意义是文件作用域的标示符。

    注:static修饰的全局变量作用域只是生命的文件中,修饰的函数作用域只是声明的文件中。

    1. register关键字

    l register关键字实名将便令存储于寄存器中。

    l register只是请求寄存器变量,但是不一定请求成功(变量的长度必须是cpu可以接受的长度)。

    注:register变量必须是cpu可以接受的值,不能用&运算符来获取register变量的地址。

    小结:

    l auto变量存储在程序的栈中,默认属性,只能修饰局部变量。

    l static变量存储在程序静态区中。

    l register变量请求存储于CPU寄存器,不能定义全局变量。在实时性要求高的时候,尽量使用。

    1. 例程

    1#include <stdio.h>

    void f1()

    {

    int i = 0;

    i++;

    printf("%d ",i);

    }

    void f2()

    {

    static int i = 0;

    i++;

    printf("%d ",i);

    }

    int main()

    {

        auto int i = 0;

        register int j = 0;

        static int k = 0;

    printf("%0X ",&i);

    //printf("%0X ",&j);  C语言只能打印内存中的地址,寄存器中的地址打印不来。

    printf("%0X ",&k);

    for(i=0; i<5;i++)

    {

    f1();

    }   //会打印51

    for(i=0;i<5; i ++)

    {

    f2();

    }//会打印12345,静态的局部变量只会被初始化一次。它的生命周期是全局的,整个程序。

        return 0;

    }

    (2)建立另一个c文件,test2.c

    l #include<stdio.h>

    int test2_g = 1;

    test1.c的内容是:

    #include <stdio.h>

    extern int test2_g ;

    int main()

    {

    printf(“%d ”,test2_g);

        return 0;

    }

    运行结果:1

    若我们将test2.c中内容改为:

    static int test2_g = 1;

    这样运行第一个程序就会出错,因为我们已经把变量限定在了程序2中。

    我们继续改,将程序2中加如下的命令:

    int test2_func()

    {

    return test2_g();

    }

    将程序1改为:

    #include <stdio.h>

    extern int test2_func() ;

    int main()

    {

    printf(“%d ”,test2_func());

        return 0;

    }

    运行结果:1

    若我们将程序2改为

    #include<stdio.h>

    static int test2_g = 1;

    static int test2_func()

    {

    return test2_g();

    }

    这样程序1再一次无法编译

    我们再次改动程序2

    #include<stdio.h>

    static int test2_g = 1;

    static int test2_func()

    {

    return test2_g();

    }

    static int test2_ff()

    {

    return test2_func();

    }

    程序1变为:

    #include <stdio.h>

    extern int test2_ff() ;

    int main()

    {

    printf(“%d ”,test2_ff());

        return 0;

    }

    运行结果:1

    以上的例子都体现了static文件限定符的作用。

  • 相关阅读:
    SAP Spartacus 自定义Popover指令,如何实现弹出对话框自动关闭功能
    SAP Spartacus B2B 页面信息提示图标的弹出窗口显示实现逻辑
    一个好用的 SAP UI5 本地打包(build)工具,自动生成Component-preload.js
    什么是 SAP UI5 的 Component-preload.js, 什么是Minification和Ugification
    云小课 | 一个三分钟快速定制OCR应用的神器,要不?
    JavaScript实现:如何写出漂亮的条件表达式
    想做测试工程师,这7件事你必须先知道
    比物理线程都好用的C++20的协程,你会用吗?
    解读 SSDB、LevelDB 和 RocksDB 到 GaussDB(for Redis) 的迁移
    数据中心太耗电,送你一个节能神器
  • 原文地址:https://www.cnblogs.com/free-1122/p/9693253.html
Copyright © 2011-2022 走看看