2016-10-11 158 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,它停止。