3.1.3 嵌套的if-else语句
如您所见,可以在if语句内嵌套if语句。同样,也可以在if语句内嵌套if-else语句,在if-else语句内嵌套if语句,以及在if-else语句内嵌套if-else语句。这种灵活性也很容易让人混淆程序,因此需要看几个示例。下面的示例是在if语句内嵌套if-else语句。
- if('y' == coffee)
- if('y' == donuts)
- cout << "We have coffee and donuts.";
- else
- cout << "We have coffee, but not donuts";
仅当coffee的测试结果返回true时,才执行对donuts的测试,因此输出消息反映的是每种情况下的正确状况,但这种嵌套结构很容易造成混淆。如果用不正确的缩进编写完全相同的代码,就可能得到错误的结论:
- if('y' == coffee)
- if('y' == donuts)
- cout << "We have coffee and donuts.";
- else // This else is indented incorrectly
- cout << "We have no coffee..."; // Wrong!
这里的错误还容易看出来,但在更复杂的if结构中,就需要记住哪个if拥有哪个else的规则。
else总是属于前面最近的、还没有对应else的if。
对于复杂的情形,可以应用这条规则来处理。当编写程序时,使用大括号肯定能使代码更清楚。在上面所示的简单情形中,大括号实际上不是必需的,但也可以将该示例写成如下形式:
- if('y' == coffee)
- {
- if('y' == donuts)
- cout << "We have coffee and donuts.";
- else
- cout << "We have coffee, but not donuts";
- }
现在的程序应该是绝对清楚的。既然我们已经知道前面的规则,就很容易理解在if-else语句内嵌套if的情形。
- if('y' == coffee)
- {
- if('y' == donuts)
- cout << "We have coffee and donuts.";
- }
- else
- if('y' == tea)
- cout << "We have tea, but not coffee";
这里的大括号是必需的。如果将其省略,则else属于第二个if,即对donuts进行测试的if。在这类情况下,通常很容易忘记添加大括号,从而产生难以发现的错误。包含这类错误的程序可以正确编译,有时甚至还能产生正确的结果。
如果删除本示例中的大括号,则仅当coffee和donuts都等于'y',从而不执行if('y' = = tea)测试时,才能得到正确结果。
下面是在if-else语句内嵌套if-else语句的示例。这种结构即使只有一级嵌套,看起来也可能非常混乱。
- if('y' == coffee)
- if('y' == donuts)
- cout << "We have coffee and donuts.";
- else
- cout << "We have coffee, but not donuts";
- else
- if('y' == tea)
- cout << "We have no coffee, but we have tea, and maybe donuts...";
- else
- cout << "No tea or coffee, but maybe donuts...";
即使有正确的缩进,该程序的逻辑也非常不明显。大括号不是必需的,因为前面学习的规则能够验证每个else都属于正确的if,但如果加上大括号,该程序看起来将更加清楚。
- if('y' == coffee)
- {
- if('y' == donuts)
- cout << "We have coffee and donuts.";
- else
- cout << "We have coffee, but not donuts";
- }
- else
- {
- if('y' == tea)
- cout << "We have no coffee, but we have tea, and maybe donuts...";
- else
- cout << "No tea or coffee, but maybe donuts...";
- }
有更好的方法来处理程序中的这种逻辑。如果将多个嵌套if语句放在一起,那么几乎肯定会在某个地方产生错误。下面一节将有助于使问题简化。