首页 > 解决方案 > 静态存储类 C++ 计数

问题描述

我是 C++ 新手,想知道为什么下面的 while 循环在编译和执行时会在 0 处停止?

#include <iostream>

void func(void);

static int count = 10;

int main() {

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

   return 0;
}


void func( void ) {
static int i = 5; // local static variable
i++;
std::cout << "i is " << i ;
std::cout << " and count is " << count << std::endl;
}

示例来自:https ://www.tutorialspoint.com/cplusplus/cpp_storage_classes.htm

标签: c++

解决方案


在 10 次循环之后,它将在 count 为零时评估 count。c++ 中的条件仅在条件不为零时才会前进,因此一旦计数达到零,它就会停止。

在最后的几个循环中,执行将如下所示:

  • 当 count 为 1 时评估条件:count 不为零,因此它继续执行循环体
  • 后缀减少计数,因此在评估条件后计数变为零
  • func() 打印出 i 和 count,现在为零。
  • 现在计算 count 为 0 的条件:条件为零,因此它停止并且不打印任何其他内容。

推荐阅读