我为什么要给If语句命名? [英] Why should i give a name to an If Statement?
问题描述
我刚刚发现我可以为For和While语句命名。我知道如果你想要打破或继续一个特定的循环它是有用的。
但为什么我应该给一个名字?它看起来没用
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
}
编译没有问题
推荐答案
如果你有一个带有名字的代码块,你可以使用break来退出它,这就是我找到的用于命名块的用法。
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
}
它也适用于没有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
}
虽然我通常使用裸露阻止而不是if。
though usually I use a bare block and not an if.
这篇关于我为什么要给If语句命名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!