How to break out of nested loops?

前端 未结 15 2695
北荒
北荒 2020-11-27 11:21

If I use a break statement, it will only break inner loop and I need to use some flag to break the outer loop. But if there are many nested loops, the code will

15条回答
  •  旧时难觅i
    2020-11-27 11:56

    No, don't spoil the fun with a break. This is the last remaining valid use of goto ;)

    If not this then you could use flags to break out of deep nested loops.

    Another approach to breaking out of a nested loop is to factor out both loops into a separate function, and return from that function when you want to exit.

    Summarized - to break out of nested loops:

    1. use goto
    2. use flags
    3. factor out loops into separate function calls

    Couldn't resist including xkcd here :)

    enter image description here

    source

    Goto's are considered harmful but as many people in the comments suggest it need not be. If used judiciously it can be a great tool. Anything used in moderation is fun.

提交回复
热议问题