do-while

// repeatedly ask user for pair of numbers to sum
  string rsp; // used in the condition; can't be defined inside the do
  do {
  cout << "please enter two values: ";
  int val1, val2;
  cin >> val1 >> val2;
  cout << "The sum of " << val1 << " and " << val2
  << " = " << val1 + val2 << "/n/n"
  << "More? [yes][no] ";
  cin >> rsp;
  } while (!rsp.empty() && rsp[0] != 'n') ;//以分号结束

循环体与之前编写的其他循环语句相似,因此很容易理解。奇怪的是此代码把 rsp 定义在 do 之前而不是在循环体内部。如果把 rsp 定义在 do 内部,那么 rsp 的作用域就被限制在 while 前的右花括号之前了。任何在循环条件中引用变量都必须在 do 语句之前就已经存在。

因为要到循环语句或者语句块执行之后,才求解循环条件,因此 do while 循环不可以采用如下方式定义变量:

  // error: declaration statement within do condition is not supported
  do {
  // ...
  mumble(foo);
  } while (int foo = get_foo()); // error: declaration in do condition

如果可以在循环条件中定义变量的话,则对变量的任何使用都将发生在变量定义之前!



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值