Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should i give a name to an If Statement?

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 specific loop.
But why should i give a name to an If?? It looks useless

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

This compiles without problems

like image 460
Oneiros Avatar asked Feb 05 '11 01:02

Oneiros


3 Answers

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.

like image 109
Sarah Happy Avatar answered Oct 09 '22 18:10

Sarah Happy


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

like image 31
PeterL Avatar answered Oct 09 '22 17:10

PeterL


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.

like image 36
Zach L Avatar answered Oct 09 '22 16:10

Zach L