C++ 专栏收录该内容
10 篇文章 0 订阅

# 形参、局部变量和静态局部变量的差别

从本质上说，三者均属于局部作用域中的变量，其中局部变量又可以分为普通（非静态）局部变量和静态局部变量。它们的差别：

1. 作用域：形参的作用域为整个函数体；而普通（非静态）局部变量和静态局部变量的作用域为：从定义处到包含该变量定义的块的结束处。
2. 初始化：形参由调用函数时所传递的实参初始化而普通（非静态）局部变量和静态局部变量通常用初始化式进行初始化，且均在程序执行流程第一次经过该对象的定义语句时惊醒初始化。静态局部变量的初始化在整个程序执行过程中只进行一次。
3. 生命周期形参和普通（非静态）局部变量均属于自动变量，在每次调用函数时创建，并在函数结束时撤销；静态局部变量的生命期跨越了函数的多次调用，它在创建后直到程序结束时才撤销。

//7-27.cpp
//读入上限值upLimt，输出1……upLimt之间所有整数的阶乘
#include <iostream>
using namespace std;

//用于辅助求阶乘的函数
int fac(int x)		//x为形参
{
static result = 1;	//result 为静态局部变量
result *= x;
return result;
}

int main()
{
int upLimt;		//upLimt为普通局部变量
cout << "Enter value of upper limit:" << endl;
cin >> upLimt;

//依次输出1……upLimt之间所有整数的阶乘
for(int i = 1; i <= upLimt; ++i)
cout << i << "! = " << fac(i) << endl;

return 0;
}

7.5. Local Objects
7.5. 局部对象
In C++, names have scope, and objects have lifetimes. To understand how functions operate, it is important to understand both of these concepts. The scope of a name is the part of the program's text in which that name is known. The lifetime of an object is the time during the program's execution that the object exists.

The names of parameters and variables defined within a function are in the scope of the function: The names are visible only within the function body. As usual, a variable's name can be used from the point at which it is declared or defined until the end of the enclosing scope.

7.5.1. Automatic Objects
7.5.1. 自动对象
By default, the lifetime of a local variable is limited to the duration of a single execution of the function. Objects that exist only while a function is executing are known as automatic objects. Automatic objects are created and destroyed on each call to a function.

The automatic object corresponding to a local variable is created when the function control path passes through the variable's definition. If the definition contains an initializer, then the object is given an initial value each time the object is created. Uninitialized local variables of built-in type have undefined values. When the function terminates, the automatic objects are destroyed.

Parameters are automatic objects. The storage in which the parameters reside is created when the function is called and is freed when the function terminates.

Automatic objects, including parameters, are destroyed at the end of the block in which they were defined. Parameters are defined in the function's block and so are destroyed when the function terminates. When a function exits, its local storage is deallocated. After the function exits, the values of its automatic objects and parameters are no longer accessible.

7.5.2. Static Local Objects
7.5.2. 静态局部对象
It is can be useful to have a variable that is in the scope of a function but whose lifetime persists across calls to the function. Such objects are defined as static.

A static local object is guaranteed to be initialized no later than the first time that program execution passes through the object's definition. Once it is created, it is not destroyed until the program terminates; local statics are not destroyed when the function ends. Local statics continue to exist and hold their value across calls to the function. As a trivial example, consider a function that counts how often it is called:

static 局部对象确保不迟于在程序执行流程第一次经过该对象的定义语句时进行初始化。这种对象一旦被创建，在程序结束前都不会撤销。当定义静态局部对象的函数结束时，静态局部对象不会撤销。在该函数被多次调用的过程中，静态局部对象会持续存在并保持它的值。考虑下面的小例子，这个函数计算了自己被调用的次数：

size_t count_calls()
{
static size_t ctr = 0; // value will persist across calls
return ++ctr;
}
int main()
{
for (size_t i = 0; i != 10; ++i)
cout << count_calls() << endl;
return 0;
}

This program will print the numbers from 1 through 10 inclusive.

Before count_calls is called for the first time, ctr is created and given an initial value of 0. Each call increments ctr and returns its current value. Whenever count_calls is executed, the variable ctr already exists and has whatever value was in the variable the last time the function exited. Thus, on the second invocation, the value is 1, on the third it is 2, and soon.

• 2
点赞
• 0
评论
• 0
收藏
• 一键三连
• 扫一扫，分享海报

03-01 8007

04-17 612
09-26 5638
11-07 186
05-04 2237
08-19 2104
08-26 1462
12-06 1319
10-04 1031
05-18 658
09-14 1734
04-02 3176
01-22 2345