c++ - 静态存储类 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
解决方案
在 10 次循环之后,它将在 count 为零时评估 count。c++ 中的条件仅在条件不为零时才会前进,因此一旦计数达到零,它就会停止。
在最后的几个循环中,执行将如下所示:
- 当 count 为 1 时评估条件:count 不为零,因此它继续执行循环体
- 后缀减少计数,因此在评估条件后计数变为零
- func() 打印出 i 和 count,现在为零。
- 现在计算 count 为 0 的条件:条件为零,因此它停止并且不打印任何其他内容。
推荐阅读
- python - Altair python - 如何为 for 中的图表对齐 x 轴(=0)
- python - pd.DataFrame 将多个数组转换为列的问题
- java - 在 Eclipse 中复制描述符
- assembly - 我的汇编函数打印一些字符串,但不是其他的
- javascript - 调用前一个兄弟作为函数参数?
- python - Python 语法:如果 C 中的 A 和 B 做某事
- java - 验证时,同一页面上的错误位置显示(类型 = 错误请求,状态 = 400)
- r - 具有 facet_grid 的同一堆积条形图中的不同填充类别
- javascript - 选择下一个 div 时取消分配背景颜色 Javascript
- r - 这是在 R 中迭代和捕获 API 输出的最简洁方法吗?