当前位置:嗨网首页>书籍在线阅读

07-何时终止循环

  
选择背景色: 黄橙 洋红 淡粉 水蓝 草绿 白色 选择字体: 宋体 黑体 微软雅黑 楷体 选择字体大小: 恢复默认

6.2.2 何时终止循环

要明确一点:只有在对测试条件求值时,才决定是终止还是继续循环。例如,考虑程序清单6.2中的程序。

程序清单6.2  when.c 程序

// when.c -- 何时退出循环
#include <stdio.h>
int main(void)
{
     int n = 5;
     while (n < 7)                    // 第7行
     {
          printf("n = %d\n", n);
          n++;                        // 第10行
          printf("Now n = %d\n", n);  // 第11行
     }
     printf("The loop has finished.\n");
     return 0;
}

运行程序清单6.2,输出如下:

n = 5
Now n = 6
n = 6
Now n = 7
The loop has finished.

在第2次循环时,变量n在第10行首次获得值7。但是,此时程序并未退出,它结束本次循环(第11行),并在对第7行的测试条件求值时才退出循环(变量n在第1次判断时为5,第2次判断时为6)。