“loop:” in Java code. What is this, and why does it compile?

后端 未结 12 1203
生来不讨喜
生来不讨喜 2020-11-22 08:02

This code just made me stare at my screen for a few minutes:

loop:
for (;;) {
    // ...
}

(line 137 here)

I have never seen this b

12条回答
  •  既然无缘
    2020-11-22 08:09

    This is really a reply to seanizer's comment on org.life.java's answer, but I wanted to put in some code so I couldn't use the comment feature.

    While it is very rare that I find a use for "break label", it does happen occassionally. The most common case is when I am searching for something that is in a structure requiring a nested loop to search, like:

    search:
    for (State state : stateList)
    {
      for (City city : state.cityList)
      {
        if (city.zipcode.equals(wantZip))
        {
          doSomethingTo(city);
          break search;
        }
      }
    }
    

    Usually in such cases I push the whole thing into a subroutine so that on a hit I can return the found object, and if it falls out the bottom of the loop I can return null to indicate a not found, or maybe throw an exception. But this is occasionally useful.

    Frankly, I think the inventors of Java included this feature because between this and exception handling, they eliminated the last two legitimate uses for GOTO.

    Very late addendum:

    I saw a great gag line of code once. The programmer wrote:

    http://www.example.com/xyz.jsp
    for (Foo foo1 : foolist)
    

    He didn't actually say "example.com" but our company's web site.

    It gives the impression that there's a URL in the code. It compiles successfully, like it does something. But ... what does it do?

    In reality it does nothing. "http:" is a label that he never references. Then the "//" makes the rest of the line a comment.

提交回复
热议问题