![](/img/trans.png)
[英]Why does the static modifier prevent its variable to be reassigned with a new value?
[英]Why does static modifier output is not consistent through function calls?
我正在重新審視靜態修飾符概念,我想知道為什么這是輸出:
this is main()
i is 6
i is 43
i is 44
i is 43
對於以下代碼:
// Example program
#include <iostream>
#include <string>
#include <cstdio>
void func()
{
static int i = 5;
printf("i is %d\n", ++i);
i = 42;
printf("i is %d\n", ++i);
}
int main()
{
puts("this is main()");
func();
func();
return 0;
}
我知道靜態意味着每個實例一個變量(至少在Java中)。 因此,我理解輸出的前三行,但是為什么靜態int
變量向右跳回到值為44然后......它向后跳,最后一個值為43?
我假設當第一個函數調用結束時,靜態變量超出范圍,但事實並非如此。 它不會被重新分配為5的值。我可能會在這里看到一些非常明顯的東西,但我根本就不明白。
static int i = 5;
...僅在第一次通話時執行。 但
i = 42;
...每次調用func()
時, i
的值都為42
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.