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';
  }
   
}

posted @ 2009-07-10 11:13  风之领域  阅读(197)  评论(0编辑  收藏  举报