C++ 是否可以将 goto 与 switch 一起使用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8202199/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is it possible to use goto with switch?
提问by Coder
It seems it's possible with C#, but I need that with C++ and preferably cross platform.
C# 似乎是可能的,但我需要 C++ 并且最好是跨平台的。
Basically, I have a switch that sorts stuff on single criteria, and falls back to default processing on everything else.
基本上,我有一个开关,可以根据单个标准对内容进行排序,并在其他所有内容上都退回到默认处理。
Say:
说:
switch(color)
{
case GREEN:
case RED:
case BLUE:
Paint();
break;
case YELLOW:
if(AlsoHasCriteriaX)
Paint();
else
goto default;
break;
default:
Print("Ugly color, no paint.")
break;
}
采纳答案by Ahmed Masud
Not quite but you can do this:
不完全,但你可以这样做:
switch(color)
{
case GREEN:
case RED:
case BLUE:
Paint();
break;
case YELLOW:
if(AlsoHasCriteriaX) {
Paint();
break; /* notice break here */
}
default:
Print("Ugly color, no paint.")
break;
}
OR you could do this:
或者你可以这样做:
switch(color)
{
case GREEN:
case RED:
case BLUE:
Paint();
break;
case YELLOW:
if(AlsoHasCriteriaX) {
Paint();
break; /* notice break here */
}
goto explicit_label;
case FUCHSIA:
PokeEyesOut();
break;
default:
explicit_label:
Print("Ugly color, no paint.")
break;
}
回答by Steve Cox
Ahmed's answer is good, but there's also:
艾哈迈德的回答很好,但也有:
switch(color)
case YELLOW:
if(AlsoHasCriteriaX)
case GREEN:
case RED:
case BLUE:
Paint();
else
default:
Print("Ugly color, no paint.");
people tend to forget how powerful switches are
人们往往会忘记开关有多么强大