开发者

Giving name to a loop

While browsing questions and answers in this forum i found a piece of code were names were given to loops in order to use them for break. Like

nameofloop:
    for(){
        for(){
             if(){ break nameofloop;}
        开发者_运维百科}
    }

Im new to programming and i havent seen that before. My question is what other uses of naming loops are there?


This is not a labeled loop, is just a label that you place anywhere and then you can "break" or "continue" to depending on your conditions. You can also use in a nested if-else with for loopings in order to break several loops decorated with if-else, so you can avoid setting lot of flags and testing them in the if-else in order to continue or not in this nested level.

Its use is discouraged as resembles a goto and causes spaghetti-code.

Personally I used only once, time ago, in order to break a for loop inside other two for loops with if-else and continue in the outer loop, as break inside a loop breaks this loop, but you continue in the outer loop, not the most-outer that was my case.


You can also say:

continue nameofloop;

...to jump to start of the named loop. I don't think there are any other use cases for labels in Java.


It's known as a labelled break which is a form of branching statement. You can see all the examples in the Official Documention.


Officially, I believe this is called a "labeled break". It's useful for breaking out of nested loops, such as:

found:
    for (int i = 0; i < 100; i++)
        for (int j = 0; j < 100; i++)
            if ( /* Some condition is met */)
                break found;

I don't think it's useful for anything else.


I think it's the only case it's used. And it's not something which is commonly used, because it's usually more readable to change the value of a flag to end a loop prematurely.


  1. Create an array (int) of size 10.

  2. Let the user assign the values - (use for-loop).

  3. Find the total and average of the values stored in the array - (use for- loop).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜