【问题标题】:while loop and static variablewhile循环和静态变量
【发布时间】:2016-10-11 08:21:44
【问题描述】:

这是我研究静态变量的代码。

#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 时循环停止了?为什么它没有走向负无穷?

【问题讨论】:

  • 也许看看while(0) 做了什么?
  • 寻找while循环的定义。直到条件为false0
  • 顺便说一句,countstatic 与问题无关。使用int count = 5; 你会得到完全相同的结果

标签: c


【解决方案1】:

因为0 等于false 值。

当count变为等于0时,while条件变为false

【讨论】:

    【解决方案2】:

    因为在你的代码中你写了

    while (count--) 
    

    在 C 中,true 定义为 0 以外的任何值,false 定义为零。当计数达到零时,您的 while 循环将停止。

    【讨论】:

      【解决方案3】:

      当你的循环到达 0 时,它会停止,因为在 while 循环中它被算作一个错误的布尔值,所以它会停止。

      【讨论】:

        【解决方案4】:

        While() 将在值为true 时执行。在这种情况下,任何正数都被视为true。另一方面,零被解释为false,从而停止循环。

        基本上While(true),做点什么。一旦到达falsewhile() 循环就会停止。

        如果你想否定,那么你需要一个 for() 循环。

        #include <stdio.h>
        
        int main()
        {
            for(int i = 10; i > -10; i--)
            {
                printf("%d", i);
            }
        
            return 0;
        }
        

        或者,如果你想使用 while(),你应该这样做:

        #include <stdio.h>
        
        int main()
        {
            int position = 10;
        
            while(position > -10)
            {
                printf("%d", position);
                position--;
            }
        
            return 0;
        }
        

        【讨论】:

        • 需要使用 for 循环”,为什么?它可能更惯用,但使用 while 也同样有效:while(i &gt; -10) { printf(...); --i; }
        • 没错,我扩展了我的答案。
        • 您的代码有一个小问题:它将打印数字之间没有空格:10987654....
        • 有问题吗? :) 代码是用来展示它是如何工作的,不是用来打印 ? 和 ? ;) 然后你可以根据需要来格式化输出。
        【解决方案5】:
        0 == false
        

        什么时候

        while (0)
        

        然后循环将停止。


        由于你也用c++ 标记了帖子,我将给你一个使用boolalpha 的c++ 示例,其中布尔值被提取并表示为truefalse

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

        现在:

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

        【讨论】:

        • 你应该解释一下boolalpha的作用,否则这个例子可能会让人困惑而不是澄清
        【解决方案6】:

        while 循环一直运行,直到它的参数不同于“false”,即 0。所以当 count 等于 0 时,它会停止。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-07-05
          • 2022-07-07
          • 1970-01-01
          • 2021-02-24
          • 2015-06-11
          相关资源
          最近更新 更多