开发者

Why should i give a name to an If Statement?

开发者 https://www.devze.com 2023-02-08 11:23 出处:网络
I just discovered that i can give a name to For and While statements. I understand that it is useful if you want to break or continue a开发者_如何学Go specific loop.

I just discovered that i can give a name to For and While statements. I understand that it is useful if you want to break or continue a开发者_如何学Go specific loop.

But why should i give a name to an If?? It looks useless

name: if(true){
    //do something
}

This compiles without problems


If you have a code block with a name, you can use break to exit it, that is the use I have found for naming blocks.

name: if(true) {
    // do something
    if(/* condition */) {
        break name;
    }
    // do more
}

it also works without the if:

name: {
    // do something
    if(/* condition */) {
        break name;
    }
    // do more
}

This comes up in my work when there are a set of guard conditions on some logic, and another set of logic that will be fallen down into regardless of the outcome of the guards.

A further example where alternative structures are more difficult to read and modify:

block: if(/* guard */) {

  // prep work

  if(/* guard */) {
    break block;
  }

  // prep work

  if(/* guard */) {
    break block;
  }

  // real work
}

though usually I use a bare block and not an if.


You can use labels before any statement block. This is maybe most commonly used for loops, but is perfectly valid elsewhere.


Sarah Happy's answer is actually more correct than mine in showing that you can use break to break code blocks, in addition to loops, so I suggest looking at her answer.


That is indeed a label, which as you said is for For and While loops. It is valid elsewhere, but I'd like to add that you cannot use

goto name;

While goto is a reserved word, Java does not support goto, but it does support it in the form of labeled loops coupled with break and continue.

If you expanded your code sample to include a goto, like:

 name: if(true){
    //do something
  }
 goto name;

You'd get errors, saying both illegal start of expression and not a statement

Alternatively, if you tried to use continue with your label, but without a loop, like:

 name: if(true){
    //do something
  }
 continue name;

You'd get undefined label: name

So in terms of the compiler, having a label without a loop is ok, but it's pretty much worthless without a loop.


Just like breaking a loop you might want to jump back or toward an if statement. Although whenever you start thinking about this, look into creating a new method instead.

0

精彩评论

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

关注公众号