c++ static/lexical scope

警告
本文最后更新于 2023-09-16,文中内容可能已过时。

C++ 是一个静态、强类型的编译型编程语言,变量的生命周期需要在编译器确定。这与动态语言是完全不同的。

Scoping is generally divided into two classes:

  1. Static Scoping (也称作 lexical scope)
  2. Dynamic Scoping

Static scoping is also called lexical scoping. In this scoping, a variable always refers to its top-level environment. This is a property of the program text and is unrelated to the run-time call stack. Static scoping also makes it much easier to make a modular code as a programmer can figure out the scope just by looking at the code. In contrast, dynamic scope requires the programmer to anticipate all possible dynamic contexts. In most programming languages including C, C++, and Java, variables are always statically (or lexically) scoped i.e., binding of a variable can be determined by program text and is independent of the run-time function call stack.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
using namespace std;

int i {999};

void f()
{
    {
        int i {10};     // in function scope
        cout << "inside f inner scrope:" << i << endl;
    }
    // i not in function scope, will search for it in the GLOBAL SCOPE
    // do not care who is calling it (other function stack)
    cout << "inside f scrope:" << i << endl;
}

int main(int argc, char *argv[])
{
    int i {20};     // int main function scope
    cout << "inside main scrope:" << i << endl;

    f();
    return 0;
}

编译后,运行得的的结果是

1
2
3
4
5
g++ /tmp/main.cpp -o /tmp/a.out && /tmp/a.out

inside main scrope:	    20
inside f inner scrope:	10
inside f scrope:		999

相关内容

william 支付宝支付宝
william 微信微信
0%