while 和 for 循环都是入口条件循环, 即在每次循环开始之前检查测试条件, 有可能根本不执行循环体中的内容.
do...while
是出口条件循环 (exit-condition loop), 在循环的每次迭代之后检测测试条件, 所以至少执行循环体中的内容一次.
do...while
循环的通用形式:
do
{
statement
} while (expression);
statement 可以是一条简单语句或复合语句.
do...while
以分号结尾.
do...while
适合那些至少执行一次的循环.
程序示例:
#include<stdio.h>
int main(void)
{
int i = 0;
do
{
printf("%d\n", i);
i++;
} while (i < 10);
return 0;
}
结果:
0
1
2
3
4
5
6
7
8
9
程序示例:
#include<stdio.h>
int main(void)
{
const int SECRET = 10;
int secret;
do
{
printf("Enter the secret: ");
scanf("%d", &secret);
} while (secret != SECRET);
printf("You are right!\n");
return 0;
}
结果:
Enter the secret: 12
Enter the secret: 11
Enter the secret: 10
You are right!
这个程序非常不安全, 一旦 scanf()
读取失败, 输入的内容会保留着内存中, 下一次还是这个内存中的内容, 还是会读取失败, 所以形成一个死循环.
改写为 while 入口循环:
#include<stdio.h>
int main(void)
{
const int SECRET = 10;
int secret;
printf("Enter the secret: \n");
scanf("%d", &secret);
while (secret != SECRET)
{
printf("Enter the secret: \n");
scanf("%d", &secret);
}
printf("You are right!\n");
return 0;
}
结果:
Enter the secret:
12
Enter the secret:
11
Enter the secret:
10
You are right!
显然程序要更长一点.
一个死循环:
#include<stdio.h>
int main(void)
{
int i = 1;
do {
if (i == 5)
continue;
printf("%d\n", i);
i++;
} while (i <= 10);
return 0;
}
打印完 1234 后进入死循环.