2011-10-07 87 views
2

我正在玩靜態關鍵字。在下面的代碼中,我無法弄清楚爲什麼x在狀態和增量之前保存它。 我期待打印1樹時間。據我所知,如果我將x聲明爲靜態,則應該發生這樣的行爲。變量保持其狀態,即使未聲明爲靜態

void print_it(void); 

    int main (int argc, const char * argv[]) 
    { 
     print_it(); 
     print_it(); 
     print_it(); 
     exit(EXIT_SUCCESS); 
    } 

    void print_it(void) 
    { 
     int x; 
     printf("%d\n", x++); 
    } 

回答

7

您尚未將x初始化爲任何值。因此,x中的初始值將會是垃圾,因爲它每次都會自增,因爲它可能每次都使用相同的內存位置。

試着改變你的代碼如下:

void print_it(void); 
int main (int argc, const char * argv[]) 
{ 
    print_it(); 
    print_it(); 
    print_it(); 
    exit(EXIT_SUCCESS); 
} 

void print_it(void) 
{ 
    int x = 0; 
    printf("%d\n", x++); 
} 
+0

我想他留下了一個靜態的聲明和x的初始化,並且他想要是指在他的'print_it'功能X,太行'INT x = 0;'應該完全移除,x應該是全局的。 – Paulpro

+0

「,因爲它可能每次都使用相同的內存位置。」完全正確,變量在堆棧上,並且因爲沒有干預代碼來擦除它,所以它保持不變。 –

+0

謝謝Aamir!這是我正在尋找的。 – jingo

0

未初始化的局部變量的初始值是不確定的。在這種情況下,該值只是坐在堆棧上並被重用,因爲您連續三次調用同一個函數。如果您調用其他具有局部變量的函數,則該值將改變,因爲其他函數將使用相同的堆棧內存。

0

沒有人,你錯了。變量不能保持其價值。你沒有初始化int x,所以每次都有garbase值 &你正在增加打印,增加了garbase值的&。

你變得一樣,但標準說它可能不一樣。

在一百萬次你得到相同的值仍然不能接受局部變量保持其值。

不同的系統與不同的環境可能你的程序有不同的價值..!

編輯: 在大多數情況下,局部變量的值爲0.所以它不保留其以前的值。

void print_it(void); 

int main (int argc, const char * argv[]) 
{ 
    print_it(); 
    print_it(); 
    print_it(); 
    return 1; 
} 

void print_it(void) 
{ 
    int x; 
    printf("starting %d\n", x); 
    x++; 
    printf("after increment %d\n", x); 
} 

如果變量保持其狀態,那麼它的輸出應該是

starting 0 
after increment 1 
starting 1 
after increment 2 
starting 2 
after increment 3 

但其真正的輸出

starting 0 
after increment 1 
starting 0 
after increment 1 
starting 0 
after increment 1 

所以現在得到點..?

局部變量不保持其狀態,但如果初始化局部變量始終值0

1

這是因爲功能print_it所有3堆佔據相同的地址空間。

// before print_it()     1st print_it();    back to main()     2nd print_it();   and so on... 
// 
// ..................    ..................   ..................    .................. 
// ... Stack data ...    ... Stack data ...   ... Stack data ...    ... Stack data ... 
// ..................    ..................   ..................    .................. 
//      <- stack_P  |call print_it()|       <- stack_P  |call print_it()| 
//            ||               ||    
//            \/               \/ 
//          ... some data ...   ... some data ...    ... some data ... 
//          | 4 bytes of x |   | X still here |    | Old X Bytes | 
//          ... some data ...   ... some data ...    ... some data ... 
//              <- stack_P             <- stack_P 
// 
//          x got incremented           x got incremented again 

試試這個主:

int main (int argc, const char * argv[]) 
{ 
    print_it(); 
    int a; 
    a += 1; 
    print_it(); 
    int b; 
    b += 2 
    print_it(); 
    exit(EXIT_SUCCESS); 
}