问题描述
我已经是静态,汽车,全局和局部变量的混乱。某处,我读了一个静态变量只能在函数内部访问,但是它们在函数返回之后仍然存在(留在记忆里)。不过,我也知道,一个局部变量也做相同的,所以有什么区别?
I’ve a bit confusion about static, auto, global and local variables. 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. 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.
的本地的变量(迂腐,与变量的块范围的)只能在声明它们code块中访问:
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
}
请注意,静态
关键字具有不同的含义除了静态存储持续时间。在全球变量或函数,它给它的内部链接的,这样它不是从其他翻译单元获得; C ++类成员,这意味着有每类中的一个实例,而不是每个对象之一。同样,在C ++中的汽车
关键字不再意味着自动存储时间;现在意味着自动型,从变量的初始化器推断出来。
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的情况下的静态,汽车,全局和局部变量之间差++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!