else虚悬问题
在嵌套语句中使用if-else语句一定要注意虚悬问题!
//错误的代码
void dieOrLive(char& thelife,int lifes)
{
if(lifes<=1||lifes>3)
//没有使用花括号,第二个if将与第一个else相匹配!
if(thelife=='*')
thelife='d';
else if(lifes==3)
if(thelife==' ')
thelife='l';
}
//正确代码,运行正确
void dieOrLive(char& thelife,int lifes)
{
if(lifes<=1||lifes>3)
{
if(thelife=='*')
thelife='d';
}
else if(lifes==3)
{
if(thelife==' ')
thelife='l';
}
}