#include<iostream>intmain(){std::cout<<"Enter a number: ";intx{};std::cin>>x;if(x>=0)// 外层if语句// 这种嵌套方式是不好的编程风格if(x<=20)// 内层if语句std::cout<<x<<" is between 0 and 20\n";return0;}
考虑下面的程序:
1 2 3 4 5 6 7 8 910111213141516171819
#include<iostream>intmain(){std::cout<<"Enter a number: ";intx{};std::cin>>x;if(x>=0)// 外层if语句// 这种嵌套方式是不好的编程风格if(x<=20)// 内层if语句std::cout<<x<<" is between 0 and 20\n";// 这个 else 应该和哪个 if 语句匹配?elsestd::cout<<x<<" is negative\n";return0;}
#include<iostream>intmain(){std::cout<<"Enter a number: ";intx{};std::cin>>x;if(x>=0)// 外层 if 语句{if(x<=20)// 内层 if 语句std::cout<<x<<" is between 0 and 20\n";else// 和内层 if 语句匹配std::cout<<x<<" is negative\n";}return0;}
这使得程序产生错误的结果:
12
Enter a number: 21
21 is negative
为了避免因嵌套 if 语句产生的歧义,最好的办法是将内部的if语句显式地定义在语句块中:
1 2 3 4 5 6 7 8 91011121314151617181920
#include<iostream>intmain(){std::cout<<"Enter a number: ";intx{};std::cin>>x;if(x>=0){if(x<=20)std::cout<<x<<" is between 0 and 20\n";else// attached to inner if statementstd::cout<<x<<" is greater than 20\n";}else// attached to outer if statementstd::cout<<x<<" is negative\n";return0;}
此时,语句块中的 else 语句会和内层的if 语句匹配,而语句块外部的 else 则和外层的 if 语句匹配。
嵌套语句展开
嵌套的多层 if 语句可以通过重新组织逻辑或使用逻辑运算符展开成一层逻辑。嵌套越少的代码越不容易出错。
例如,上面的例子中可以展开成如下形式:
1 2 3 4 5 6 7 8 91011121314151617
#include<iostream>intmain(){std::cout<<"Enter a number: ";intx{};std::cin>>x;if(x<0)std::cout<<x<<" is negative\n";elseif(x<=20)// only executes if x >= 0std::cout<<x<<" is between 0 and 20\n";else// only executes if x > 20std::cout<<x<<" is greater than 20\n";return0;}
下面是另一个使用逻辑运算符在一个if语句中检查多个条件的例子:
1 2 3 4 5 6 7 8 9101112131415161718192021
#include<iostream>intmain(){std::cout<<"Enter an integer: ";intx{};std::cin>>x;std::cout<<"Enter another integer: ";inty{};std::cin>>y;if(x>0&&y>0)// && 是逻辑与——检查是否两个条件均为真std::cout<<"Both numbers are positive\n";elseif(x>0||y>0)// || 是逻辑或——检查是否有为真的条件std::cout<<"One of the numbers is positive\n";elsestd::cout<<"Neither number is positive\n";return0;}