2016-10-11 156 views
-9

這是我從哪裏學習靜態變量的代碼。while循環和靜態變量

#include <stdio.h> 

/* function declaration */ 
void func(void); 

static int count = 5; /* global variable */ 

main() { 

    while(count--) { 
     func(); 
    } 

    return 0; 
} 

/* function definition */ 
void func(void) { 

    static int i = 5; /* local static variable */ 
    i++; 

    printf("i is %d and count is %d\n", i, count); 
} 

我編譯和運行這個終端上,並得到了這個輸出

i is 6 and count is 4 
i is 7 and count is 3 
i is 8 and count is 2 
i is 9 and count is 1 
i is 10 and count is 0 

我查詢時count值等於0爲什麼循環停止?爲什麼它不會走向負面的無限?

+9

也許看看'while(0)'做些什麼? – juanchopanza

+3

http://en.cppreference.com/w/cpp/language/ while – SingerOfTheFall

+6

尋找'while'循環的定義。直到條件爲「假」或「0」。 – Gravell

回答

0

,因爲在你的代碼中寫道

while (count--) 

,並用C真正被定義爲0以外的任何東西,假的定義爲零。當計數達到零時,while while循環停止。

4

因爲0等於false的值。

當計數變成等於0時,while條件變爲false

0

當你的循環達到0時,它會停止,因爲在while循環中它被視爲一個假的布爾值,所以它會停止。

0

while()將在值爲true時執行。在這種情況下,任何正數都被視爲true。另一方面,零被解釋爲false,從而停止循環。

基本上While(true),做些什麼。一旦你達到falsewhile()循環停止。

如果你想消極,那麼你需要一個爲()循環。

#include <stdio.h> 

int main() 
{ 
    for(int i = 10; i > -10; i--) 
    { 
     printf("%d", i); 
    } 

    return 0; 
} 

或者,如果你想使用,而(),你應該這樣來做:

#include <stdio.h> 

int main() 
{ 
    int position = 10; 

    while(position > -10) 
    { 
     printf("%d", position); 
     position--; 
    } 

    return 0; 
} 
+2

「**需要**用於循環」,爲什麼?它可能更習慣性,但使用'while'也可以:'while(i> -10){printf(...); - 一世; }' – hyde

+0

沒錯,我擴展了我的答案。 –

+0

你的代碼存在一個小問題:它會在它們之間沒有空格的情況下打印數字:'10987654 ....'。 – mch

0
0 == false 

while (0) 

然後循環將停止。


既然你標記c++後也一樣,我會給你在C++中使用boolalpha,其中布爾值被提取並表示無論是truefalse一個例子:

bool b = -5; 
cout << boolalpha << b; // outputs: true 

現在:

bool b = 0; 
cout << boolalpha << b; // outputs: false 
+0

你應該解釋一下'boolalpha'的作用,否則這個例子可能會比闡明更困惑 – user463035818

0

while循環運行,直到它的參數不同於「false」,它是0.因此,當c ount等於0,它停止。