zoukankan      html  css  js  c++  java
  • Static and Local Scope

    Someone says, " I just want to define a int var in a .h file. Who pa Who?

    Now we see the following example.

    Static: Local in YOU

    ---------------ah.h-----------------

    static int a=1;

    ------------------------------

    ----------------callseta.cpp--------------

    #include"ah.h"

    #include<iostream>

    using namespace std;

    void seta()

    {

      a=2;

      //cout<<"call seta()"<<endl;

      //cout<<"in call, a="<<a<<endl;

    }

    --------------------------------------------

    -----------------main.cpp---------------

    #include"ah.h"

    #include<iostream>

    extern void seta();

    using namespace std;

    void main()

    {

      cout<<"a="<<a<<endl;

      seta();

      cout<<"after seta()"<<endl;

      cout<<"a="<<a<<endl;

    }

    -----------------------------------

    output  :

    a=1
    call seta()
    in call, a=2
    after seta()
    a=1
    请按任意键继续. . .

    ----------------------------------

    this a is local in main.cpp. For include" ", the a is static.

    So there are two "int a", one in main.cpp's scope or workspace, the other in callseta.cpp's scope.

    They are two different int var, with different address allocated.

    They only live in their own world. Any guy outside can not see her beauty.

    Interesting things are:

    when you call seta() in main.cpp, the pointer turns to the program space of callseta.cpp.

    It is not realized that firstly clone the program to the main.cpp 's program data segament.

    The pointer turns onto the orginal and the only one program data segament of seta() in callseta.cpp.

    So in that scope, a means his a, not the a in main, which is amazing.

  • 相关阅读:
    配置webstorm使用supervisor时出现 /usr/bin/env: node: 没有那个文件或目录 解决方法
    解决Ubuntu不能挂载ntfs格式硬盘
    git远程操作
    git重写历史记录
    git撤销命令
    git查看历史命令
    git分支管理和stash
    git的忽略文件和删除文件操作
    homebrew学习(四)之取消homebrew自动更新
    homebrew学习(三)之homebrew命令
  • 原文地址:https://www.cnblogs.com/stevenxiu/p/5557526.html
Copyright © 2011-2022 走看看