C语言 用于 switch-case-break 语句的“case”中的 if、else-if 和 else 语句?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7734118/
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
If, else-if, and else statements inside a "case" for a switch-case-break statement?
提问by Arthur Collé
I know the syntax for writing a case break statement, but I'm wondering if this is allowed:
我知道编写 case break 语句的语法,但我想知道是否允许这样做:
CODE:
代码:
case 'p':
{
printf("Give number: ");
scanf("%d, &int_1);
if int_1=5;{
printf("Played: you win");
}
break;
}
Basically I'm just wondering if this is something that's possible to do, I know the code is incomplete but I don't want anyone to think I'm trying to elicit specific answers. I simply seek a better understanding of applying conditionals to my programs. Thank you.
基本上,我只是想知道这是否可行,我知道代码不完整,但我不希望任何人认为我在试图引出具体的答案。我只是寻求更好地理解将条件应用于我的程序。谢谢你。
EDIT: Other than in the tags, I didn't specify so just in case this isn't clear, this is in C.
编辑:除了在标签中,我没有指定,以防万一这不清楚,这是在 C 中。
回答by Mysticial
Yes it's allowed. But you also forgot the (parentheses)around your if:
是的,这是允许的。但你也忘了(括号)在你的if:
if int_1=5;{
should be:
应该:
if (int_1 == 5){
So if it wasn't compiling, this is the reason.
所以如果它没有编译,这就是原因。
回答by Jerry Coffin
The short answer is yes, you can nest an ifinside of swtich/casestatement (or vice versa). If you want to badly enough, you could have a loop containing a switchcontaining several ifs, etc.
简短的回答是肯定的,您可以if在swtich/case语句内部嵌套(反之亦然)。如果你想要足够糟糕,你可以有一个包含switch包含多个ifs 等的循环。
Bottom line: the limit on nesting various kinds of statements is normally imposed by such considerations as taste and readability, not limitations built into the language.
底线:嵌套各种语句的限制通常是出于品味和可读性等考虑,而不是语言内置的限制。

