8-9 do while 语句
假设我们需要向用户展示菜单并要求其进行选择——若用户选择无效选项,则需再次询问。显然菜单和选择逻辑应置于某种循环结构中(以便持续询问直至获得有效输入),但该选用何种循环?
由于while循环会预先求值条件,因此是个不理想的选择。我们可以这样解决问题:
#include <iostream>
int main()
{
// selection must be declared outside while-loop, so we can use it later
int selection {}; // value initialized to 0
while (selection < 1 || selection > 4)
{
std::cout << "Please make a selection: \n";
std::cout << "1) Addition\n";
std::cout << "2) Subtraction\n";
std::cout << "3) Multiplication\n";
std::cout << "4) Division\n";
std::cin >> selection;
}
// do something with selection here
// such as a switch statement
std::cout << "You selected option #" << selection << '\n';
return 0;
}

但这仅在初始值0不在有效值集合(1、2、3或4)中时才成立。若0成为有效选项呢?我们必须另选初始化值来表示“无效”——此时代码便引入了魔数(5.2节——字面量)。
我们不妨新增一个变量来追踪有效性,例如:
#include <iostream>
int main()
{
int selection {};
bool invalid { true }; // new variable just to gate the loop
while (invalid)
{
std::cout << "Please make a selection: \n";
std::cout << "1) Addition\n";
std::cout << "2) Subtraction\n";
std::cout << "3) Multiplication\n";
std::cout << "4) Division\n";
std::cin >> selection;
invalid = (selection < 1 || selection > 4);
}
// do something with selection here
// such as a switch statement
std::cout << "You selected option #" << selection << '\n';
return 0;
}
虽然这样避免了使用魔数,但引入了一个新变量,仅仅是为了确保循环执行一次,这增加了复杂性并可能导致额外的错误。
Do while 语句
为了解决上述问题,C++ 提供了 do-while 语句:
do
statement; // can be a single statement or a compound statement
while (condition);
do-while语句do while statement是一种循环结构,其工作原理与while循环相同,但区别在于该语句至少会执行一次。在语句执行完毕后,do-while循环才会检查条件。若条件求值为真,执行路径将跳转回do-while循环的顶部并重新执行该循环。
以下是我们上述示例中使用do-while循环替代while循环的实现:
#include <iostream>
int main()
{
// selection must be declared outside of the do-while-loop, so we can use it later
int selection {};
do
{
std::cout << "Please make a selection: \n";
std::cout << "1) Addition\n";
std::cout << "2) Subtraction\n";
std::cout << "3) Multiplication\n";
std::cout << "4) Division\n";
std::cin >> selection;
}
while (selection < 1 || selection > 4);
// do something with selection here
// such as a switch statement
std::cout << "You selected option #" << selection << '\n';
return 0;
}
通过这种方式,我们既避免了魔数,又省去了额外变量。
上述示例中值得探讨的是:选择变量必须在do代码块外部声明。若在do代码块内部声明,该变量将在do代码块结束时被销毁——此时条件判断尚未执行。但while循环条件需要该变量,因此选择变量必须置于do代码块外部(即使函数主体后续未使用该变量)。
实际开发中,do-while循环并不常见。将条件置于循环末尾会模糊循环逻辑,容易引发错误。因此许多开发者建议完全避免使用do-while循环。我们持更温和的态度:在选择余地相同时,建议优先采用while循环替代do-while。
最佳实践
在等效选项中,优先选择while循环而非do-while循环。

浙公网安备 33010602011771号