📑 Table of Contents

计算机科学中,局部变量(英語:local variables是拥有局部作用域变量。这样的变量只能由声明它的函数中访问。在仅有两层可见性的程序设计语言中,局部变量对应全局变量;另一方面,许多类ALGOL语言允许任意多层的嵌套函数英语Nested function,各自拥有私有变量、函数、常量和类型。

大多数程序设计语言中,局部变量是直接存储在调用堆栈上的自动变量。即递归函数调用自己时,局部变量的每一份实例都在不同的地址空间中。于是在当前作用域对变量的声明、写入、读取都不会在其被声明的函数外产生副作用

静态局部变量

编辑

静态局部变量(英語:static local variables)是一类特殊的局部变量,许多主流语言(C/C++Visual BasicVB.NET等)中都有该变量。静态局部变量的值将一直保留,即便一个函数结束,另一个函数开始使用该变量。换言之,它是局部范围(local scope)的静态变量

静态局部变量 和 静态全局变量(英語:static global variables)的生命周期一样,它们会存活到程序结束为之。[1]它们的区别:静态局部变量只可被一个函数访问(function scope), 静态全局变量 可被所有函数访问(global scope)。

#include <iostream>
using namespace std;

void test()
{
    // var是一个静态局部变量
    static int var = 0;
    ++var;

    cout << var << endl;
}

int main()
{
    
    test(); // 输出1
    test(); // 输出2

    return 0;
}

闭包(英語:Closure)同样可以做到静态局部变量的效果。

另见

编辑

参考资料

编辑
  1. ^ Current C standardPDF(3.61 MB) (截至2009年 (2009-Missing required parameter 1=month!)). 注意第32页章节 6.2.4《Storage durations of objects》。

📚 Artikel Terkait di Wikipedia

B語言

note: auto declares a variable with automatic storage (lifetime is function scope), not "automatic typing" as in C++11. */ if (a = n / b) /* assignment

LISP

and constructs like labels to extend the scope of variables beyond a single function. In PicoLisp, function definitions are normal symbol values. They

立即调用函数表达式

Developer Network. [4 February 2013]. (原始内容存档于2013-05-25).  Functions and function scope. Mozilla JavaScript Reference. Mozilla Developer Network. [4 February

名字解析 (程序设计)

outer scope public void setFoo(int foo) { // A declaration with the same name in the inner scope // "foo" is resolved by looking in the innermost scope first

匿名函数

without the need to have those variables exist in the lambda function’s enclosing scope. The initialization can be expressed as any arbitrary expression;

RAII

ScopeGuard和Boost.ScopeExit就是RRID的典型应用: #include <functional> class ScopeGuard { private: typedef std::function<void()> destructor_type;

Kotlin

interpolation)。 类型推断也是支持的。 // Hello, world! 範例 fun main() { val scope = "World" println("Hello, $scope!") } fun main(args: Array<String>) { for (arg in args) {

续体

storable. The possibility of assigning an escape object to a variable whose scope extends beyond the CATCH which created the object can be exploited to "return