// 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
如果可以在循环条件中定义变量的话,则对变量的任何使用都将发生在变量定义之前!
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
如果可以在循环条件中定义变量的话,则对变量的任何使用都将发生在变量定义之前!