• 理解全局变量,局部变量,静态全局变量,静态局部变量


    糊涂了很久,看了别人的解释,似懂非懂的。今天终于看了stackoverflow里面的解释。自己写了点程序验证了下,终于明白了。

    局部变量:作用域在一个block里

    例如

    if(ture)
    {
    int i = 0;
    }

    i就是局部变量,作用域就在大括号里。

    再看

    function()
    {
    = 0;
    }

     局部变量实质在存放在函数的栈中,每一次invoke函数,都会产生变量i,多次调用i之间是不受影响的。

    #include <iostream>
    void f();
    int main()
    {
    f();
    f();
    return 0;
    }

    void f()
    {
        std::
    string localA;
        localA 
    += "ab";
        std::cout 
    << localA<<"\n";
    }

     

    静态局部变量:作用域在namespace scope and local scope and class scope,内存存放在Global data中。但是对于函数的多次调用,是shared变量的值的,因为它不存放在函数栈里面嘛,这个解释的通。

    例子:

    #include <iostream>
    void f();
    int main()
    {
    f();
    f();
    return 0;
    }

    void f()
    {
        
    static std::string localA;
        localA 
    += "ab";
        std::cout 
    << localA<<"\n";
    }

    全局变量存放地和静态变量一致,但是作用域是定义全局变量的文件scope。如果其他文件需要使用这个变量,需要用extern声明。

    全局静态变量同样存放在global里,但是其作用域在translation unit。

    下面是关于translation unit的解释:本source文件+include的文件。

    A source file toghether with all the headers and source files included via the preprocessing directive #include less any source line skipped by any of the conditional inclusion preprocessing directives is called a translation unit.
    A "translation unit" is a source file plus any headers or other source files it #includes, plus any files that THEY include, and so on. A source file is just that...one source file.

    A translation unit is the basic unit of compilation in C++. It contains:

    • all the contents of a single source file after the preprocessor has run its course
    • the contents of any header files directly or indirectly included by it
    • minus any lines ignored using conditional preprocessing statements

    A single translation unit gets compiled into an object file, library, or executable program.

    A source file, by contrast, is a stand-alone file, just like any other file on your file system. Once compiled, it can be a component of a translation unit as mentioned above.

     

  • 相关阅读:
    01 Sonic 简介
    使用中科院Mirrors的brew镜像源来安装brew
    vueelementadmin修改顶部导航栏
    02 Sonic 调试、发布 agent
    04 Sonic 调试 server
    05 Sonic 修改iso无法远控传图问题(前端解决跨域问题)
    06 Sonic 实现多设备运行
    工作方法论思考总结
    git中出现error: Your local changes to the following files would be overwritten by merge的解决方案
    git rebase master
  • 原文地址:https://www.cnblogs.com/smartvessel/p/2014768.html
Copyright © 2020-2023  润新知