问题描述
我对 static
、auto
、global
和 local
变量有点困惑.
I’ve a bit confusion about static
, auto
, global
and local
variables.
我在某处读到 static
变量只能在函数内访问,但在函数返回后它们仍然存在(保留在内存中).
Somewhere I read that a static
variable can only be accessed within the function, but they still exist (remain in the memory) after the function returns.
不过,我也知道local
变量也有同样的作用,那么有什么区别呢?
However, I also know that a local
variable also does the same, so what is the difference?
推荐答案
这里有两个独立的概念:
There are two separate concepts here:
- 范围,它决定了可以访问名称的位置,以及
- 存储持续时间,决定了何时创建和销毁变量.
- scope, which determines where a name can be accessed, and
- storage duration, which determines when a variable is created and destroyed.
局部变量(迂腐地,具有块作用域的变量)只能在声明它们的代码块内访问:
Local variables (pedantically, variables with block scope) are only accessible within the block of code in which they are declared:
void f() {
int i;
i = 1; // OK: in scope
}
void g() {
i = 2; // Error: not in scope
}
全局变量(迂腐地,具有文件范围(在C中)或命名空间范围(在C++中)的变量)可以在任何时候访问在他们声明之后:
Global variables (pedantically, variables with file scope (in C) or namespace scope (in C++)) are accessible at any point after their declaration:
int i;
void f() {
i = 1; // OK: in scope
}
void g() {
i = 2; // OK: still in scope
}
(在 C++ 中,情况更加复杂,因为命名空间可以关闭和重新打开,并且可以访问当前范围以外的范围,并且名称也可以具有类范围.但这变得非常偏离主题.)
(In C++, the situation is more complicated since namespaces can be closed and reopened, and scopes other than the current one can be accessed, and names can also have class scope. But that's getting very off-topic.)
自动变量(迂腐,具有自动存储持续时间的变量)是局部变量,其生命周期在执行离开其作用域时结束,并在重新进入作用域时重新创建.
Automatic variables (pedantically, variables with automatic storage duration) are local variables whose lifetime ends when execution leaves their scope, and are recreated when the scope is reentered.
for (int i = 0; i < 5; ++i) {
int n = 0;
printf("%d ", ++n); // prints 1 1 1 1 1 - the previous value is lost
}
静态变量(迂腐地,具有静态存储期的变量)的生命周期一直持续到程序结束.如果它们是局部变量,那么当执行离开它们的作用域时它们的值仍然存在.
Static variables (pedantically, variables with static storage duration) have a lifetime that lasts until the end of the program. If they are local variables, then their value persists when execution leaves their scope.
for (int i = 0; i < 5; ++i) {
static int n = 0;
printf("%d ", ++n); // prints 1 2 3 4 5 - the value persists
}
请注意,static
关键字除了静态存储持续时间之外还有多种含义.在全局变量或函数上,它赋予它内部链接,以便其他翻译单元无法访问它;在 C++ 类成员上,这意味着每个类有一个实例,而不是每个对象一个.此外,在 C++ 中,auto
关键字不再表示自动存储持续时间;它现在意味着从变量的初始值设定项推导出的自动类型.
Note that the static
keyword has various meanings apart from static storage duration. On a global variable or function, it gives it internal linkage so that it's not accessible from other translation units; on a C++ class member, it means there's one instance per class rather than one per object. Also, in C++ the auto
keyword no longer means automatic storage duration; it now means automatic type, deduced from the variable's initialiser.
这篇关于c和c++上下文中静态、自动、全局和局部变量的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!