C语言中do-while语句的2种写法示例

所属分类: 软件编程 / C 语言 阅读数: 116
收藏 0 赞 0 分享

while循环和for循环都是入口条件循环,即在循环的每次迭代之前检查测试条件,所以有可能根本不执行循环体中的内容。C语言还有出口条件循环(exit-condition loop),即在循环的每次迭代之后检查测试条件,这保证了至少执行循环体中的内容一次。这种循环被称为do while循环。

看下面的例子:

#include <stdio.h>
int main(void)
{
 const int secret_code = 13;
 int code_entered;

 do
 {
  printf("To enter the triskaidekaphobia therapy club,\n");
  printf("please enter the secret code number: ");
  scanf("%d", &code_entered);
 } while (code_entered != secret_code);
 printf("Congratulations! You are cured!\n");

 return 0;
}

运行结果:

To enter the triskaidekaphobia therapy club,

please enter the secret code number: 12

To enter the triskaidekaphobia therapy club,

please enter the secret code number: 14

To enter the triskaidekaphobia therapy club,

please enter the secret code number: 13

Congratulations! You are cured!

使用while循环也能写出等价的程序,但是长一些,如程序清单6.16所示。

#include <stdio.h>
int main(void)
{
 const int secret_code = 13;
 int code_entered;

 printf("To enter the triskaidekaphobia therapy club,\n");
 printf("please enter the secret code number: ");
 scanf("%d", &code_entered);
 while (code_entered != secret_code)
 {
  printf("To enter the triskaidekaphobia therapy club,\n");
  printf("please enter the secret code number: ");
  scanf("%d", &code_entered);
 }
 printf("Congratulations! You are cured!\n");

 return 0;
}

下面是do while循环的通用形式:

do
 statement
while ( expression );

statement可以是一条简单语句或复合语句。注意,do-while循环以分号结尾。

Structure of a =do while= loop=

do-while循环在执行完循环体后才执行测试条件,所以至少执行循环体一次;而for循环或while循环都是在执行循环体之前先执行测试条件。do while循环适用于那些至少要迭代一次的循环。例如,下面是一个包含do while循环的密码程序伪代码:

do
{
 prompt for password
 read user input
} while (input not equal to password);

避免使用这种形式的do-while结构:

do
{
 ask user if he or she wants to continue
 some clever stuff
} while (answer is yes);

这样的结构导致用户在回答“no”之后,仍然执行“其他行为”部分,因为测试条件执行晚了。

总结

更多精彩内容其他人还在看

C++ COM编程之接口背后的虚函数表

这篇文章主要介绍了C++ COM编程之接口背后的虚函数表,COM的背后,就是接口,而接口的背后,就是虚函数表,需要的朋友可以参考下
收藏 0 赞 0 分享

C++设计模式之装饰模式

这篇文章主要介绍了C++设计模式之装饰模式,装饰模式能够实现动态的为对象添加功能,是从一个对象外部来给对象添加功能,需要的朋友可以参考下
收藏 0 赞 0 分享

C++ COM编程之QueryInterface函数(一)

这篇文章主要介绍了C++ COM编程之QueryInterface函数(一),QueryInterface是组件本身提供对自己查询的一个接口,需要的朋友可以参考下
收藏 0 赞 0 分享

C++ COM编程之QueryInterface函数(二)

这篇文章主要介绍了C++ COM编程之QueryInterface函数(二),本文是第二篇,第一篇请参阅相关文档,需要的朋友可以参考下
收藏 0 赞 0 分享

C++中的类型转换static_cast、dynamic_cast、const_cast和reinterpret_cast总结

这篇文章主要介绍了C++中的类型转换static_cast、dynamic_cast、const_cast和reinterpret_cast总结,需要的朋友可以参考下
收藏 0 赞 0 分享

C++设计模式之外观模式

这篇文章主要介绍了C++设计模式之外观模式,本文详细讲解了C++中的Facade模式,并给出了实例代码,需要的朋友可以参考下
收藏 0 赞 0 分享

C++构造函数初始化顺序详解

这篇文章主要介绍了C++构造函数初始化顺序详解,是对C++代码的运行机制深入探讨,需要的朋友可以参考下
收藏 0 赞 0 分享

C++交换指针实例

这篇文章主要介绍了C++交换指针实例,针对C与C++交换指针的方法进行了较为详细的对比分析,非常具有实用价值,需要的朋友可以参考下
收藏 0 赞 0 分享

基于C++实现的线程休眠代码

这篇文章主要介绍了基于C++实现的线程休眠代码,包括了Linux平台及基于boost库的两种实现方法,有不错的参考借鉴价值,需要的朋友可以参考下
收藏 0 赞 0 分享

C++常用字符串分割方法实例汇总

这篇文章主要介绍了C++常用字符串分割方法实例汇总,包括了strtok函数、STL、Boost等常用的各类字符串分割方法,非常具有实用价值,需要的朋友可以参考下
收藏 0 赞 0 分享
查看更多