問題描述
我對 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++上下文中靜態、自動、全局和局部變量的區別的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!