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
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.