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


    糊涂了很久,看了别人的解释,似懂非懂的。今天终于看了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.

     

  • 相关阅读:
    JQuery常用的api[最好是系统地学习一下《锋利的JQuery》]
    soapui icon以及resource的理解
    《Effective C++ 》学习笔记——条款02
    android移植pppoe拨号上网的全过程
    tomcat dbcp 基于jndi当配置java.sql.SQLException: Already closed
    【iOS】文件下载小记
    Amazon S3数据一致性模型
    ARM裸编程系列---UART
    如何做程序猿SOHO它定购家庭赚外快?
    HDU 4940(杭电更多的学校#7 1006) Destroy Transportation system(到处乱混)
  • 原文地址:https://www.cnblogs.com/smartvessel/p/2014768.html
Copyright © 2020-2023  润新知