首頁 > 後端開發 > C++ > 與全域變數和局部變數相比,函數級靜態變數在分配和初始化方面有何不同?

與全域變數和局部變數相比,函數級靜態變數在分配和初始化方面有何不同?

Patricia Arquette
發布: 2024-11-15 10:25:02
原創
243 人瀏覽過

How Do Function-Level Static Variables Differ in Allocation and Initialization Compared to Global and Local Variables?

Function-Level Static Variable Allocation and Initialization: A Deeper Dive

While global variables are typically allocated and initialized upon program start, the allocation and initialization of function-level static variables follow a more nuanced pattern.

When Function-Level Static Variables Get Allocated

Unlike global variables, function-level static variables are allocated when the function is first entered. This is in contrast to the allocation of local variables, which happens every time the function is called.

When Function-Level Static Variables Get Initialized

The initialization of function-level static variables occurs only once, the first time the function is entered. This is because the static keyword ensures that the variable retains its value across multiple function calls.

An Example for Clarity

Consider the following code snippet:

void doSomething() {
  static bool globalish = true;
  // ...
}
登入後複製

When the program execution reaches the doSomething function for the first time, the globalish variable will be allocated in the function's stack frame. Then, its initialization to true will take place. On subsequent calls to the doSomething function, the globalish variable will already be allocated and initialized, and its value will be preserved.

Conclusion

In summary, function-level static variables get allocated when the function is first entered and get initialized only once, during that first entry. This behavior differs from both global variables and local variables, providing a unique and useful mechanism for maintaining persistent data within functions.

以上是與全域變數和局部變數相比,函數級靜態變數在分配和初始化方面有何不同?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板