static:
static 若加在 local variable 上,那 static local variable 的壽命跟 global variable 一樣長,但是只在宣告的 { }區間內是可視的,也就是只有在 { } 區間內可以存取,但是其值在離開區間後仍會保留,一直存在記憶體之中,且初始化只會有一次。

void function()
{
      static int cnt = 0; // count 只有第一次會初始化成 0
      cnt++;

      cout << cnt << endl;
}

int main()

{
     function();
     function();
}

輸出結果會是:
1
2
因為初始化只有一次,function 被執行幾次,count 就會是多少。

 

extern:
可以聲明變數會在其它的位置被定義,可能是在同一份文件之中,或是在其它文件。

Ex:

other.cpp

double num = 1000;
// 其它定義 …

main.cpp

int main() 
{
    extern double num = 100;
    cout << num << endl;
    return 0;
}

在 main.cpp 中並沒有宣告num,但 extern 指出 num 是在其它位置被定義,因此編譯器會在其它位置或文件中找出 num 的定義,因而顯示結果為1000。另外,如果在使用 extern 時同時指定其值,則視為在該位置定義變數,結果就造成重覆定義錯誤。

Ex: (重覆定義錯誤)

int main() {
    extern double num = 100;
    cout << num << endl;
    return 0;
}


必須先聲明extern找到變數,再重新指定其值,這麼使用才是正確的

 

int main(void) {
    extern double num;
    num = 100;
    return 0;
}

 

資料來源:
http://openhome.cc/Gossip/CGossip/Scope.html

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 胖打打 的頭像
    胖打打

    Keep learning

    胖打打 發表在 痞客邦 留言(0) 人氣()