如何从深层嵌套的循环中迅速跳出

因为break一次只能跳出一层循环,所以如果想从多层嵌套中迅速跳出有以下方法:

1、goto语句

while(condition1)

{

  while(condition2)

  {

    while(condition3)

      if(some disaster)

        goto quit;

  }

}

quit:

   ;

2、设置一个状态标志:

enum {EXIT ,OK}status;

...

status = OK;

while(status == OK && condition1)

{

  while(status == OK && condition2)

     {

    while(status == OK && condition3)

      if(some disaster)

      {

        status  = EXIT;

        break;

      }

  }

}

3、单独设置一个函数,if disaster的时候,就用return语句离开这个函数。

posted on 2011-07-12 10:05  dusts  阅读(1178)  评论(0编辑  收藏  举报

导航