c static靜態變數用法

來源:互聯網
上載者:User

所有未加static首碼的全域變數和函數都具有全域可見度。為理解這句話,我舉例來說明
static的第三個作用是預設初始化為0。其實全域變數也具備這一屬性,因為全域變數也儲存在待用資料區。在待用資料區,記憶體中所有的位元組預設值都是0x00,某些時候這一特點可以減少程式員的工作量

#include <stdio.h>

int g = 10; 

main(){

    int i =0;
    void f1();
    f1();           
    printf(" after first call n");
    f1();           
    printf("after second call n");
    f1();           
    printf("after third call n");

}
void f1()
{
    static int k=0; 
    int j = 10;            
    printf("value of k %d j %d",k,j);
    k=k+10;
}

利用static實現全域變數賦值方法
儲存在待用資料區的變數會在程式剛開始運行時就完成初始化,也是唯一的一次初始化。共有兩種變數儲存在靜態儲存區:全域變數和static變數,只不過和全域變數比起來,static可以控制變數的可見範圍,說到底static還是用來隱藏的

#include <stdio.h>

void test1(void){
  int count = 0;
  printf("ntest1   count = %d ", ++count );
}

void test2(void){
  static int count = 0;
  printf("ntest2   count = %d ", ++count );
}

int main(void)
{
  int i;
  for(i = 0; i < 5; i++ )
  {
    test1();
    test2();
  }
  return 0;
}

輸出值為

test1   count = 1
     test2   count = 1
     test1   count = 1
     test2   count = 2
     test1   count = 1
     test2   count = 3
     test1   count = 1
     test2   count = 4
     test1   count = 1
     test2   count = 5

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.