[英]Why can't you use || in a switch case?
I'm currently learning the basics in C programming and was about to try out the switch-statement. 我目前正在学习C编程的基础知识,并打算尝试使用switch语句。 My questions is: 我的问题是:
switch (answer)
{
case ('Y' || 'y') :
printf("\nYay! Me too. ");
break;
case ('N' || 'n') :
printf("\nBoo! :(");
break;
default:
printf("\nInput error!");
break;
}
Why can't I write an || 为什么我不能写|| in my different cases? 在我的不同情况下?
switch case doesn't support logical operations. 开关盒不支持逻辑操作。 In your case the solution is easy: 您的解决方案很简单:
switch (answer)
{
case 'Y':
case 'y':
printf("\nYay! Me too. ");
break;
case 'N':
case 'n':
printf("\nBoo! :(");
break;
default:
printf("\nInput error!");
break;
}
First of all, switch requires the
case` expressions to be constants, so expressions aren't allowed. 首先,switch requires the
case的表达式为常量,因此不允许使用表达式。
But even if expressions were allowed (as it is in other languges that have copied much of C's syntax, like PHP and Javascript), it wouldn't do what you want. 但是,即使允许使用表达式(就像复制了C大部分语法的其他语言一样,如PHP和Javascript),它也不会做您想要的事情。 The statement 该声明
case <value>:
is analogous to: 类似于:
if (answer == (<value>))
So if you write: 因此,如果您写:
case ('N' || 'n'):
it's like: 就像是:
if (answer == ('N' || 'n'))
The expression 'N' || 'n'
表达式'N' || 'n'
'N' || 'n'
is evaluated as a boolean, which returns 1
. 'N' || 'n'
被评估为布尔值,返回1
。 So it's equivalent to: 因此,它等效于:
case (1):
which is obviously not what you want. 这显然不是您想要的。
You can either use 您可以使用
switch (tolower(answer)):
and then you only have to compare with the lowercase letter, or you can use the fall-through behavior of multiple case
statements: 然后您只需要与小写字母进行比较,或者可以使用多个case
语句的直通行为:
case 'N':
case 'n':
The constant-expression for a case must be the same data type as the variable in the switch, and it must be a constant or a literal. 案例的常量表达式必须与开关中的变量具有相同的数据类型,并且必须是常量或文字。
Do something like the following: 执行以下操作:
case 'Y':
case 'y':
printf("Got a Y!");
break;
Because the value given to case is not a boolean. 因为case的值不是布尔值。
You can use fall-through to achieve the effect you are looking for: 您可以使用穿透效果来实现所需的效果:
switch(answer) {
case 'Y':
case 'y':
printf... etc
Switch
requires constant expressions. Switch
需要常量表达式。 You have two options here: 您在这里有两个选择:
1) Using fall through 1)使用跌倒
switch (answer)
{
case 'a':
case 'b':
<code for 'a' or 'b'>
break;
}
2) In this particular case, you can normalize your input, using something analogous to a tolower
function. 2)在这种特殊情况下,您可以使用类似于tolower
函数的方式对输入进行标准化。 For example: 例如:
switch (tolower(answer))
{
case 'a':
<code for 'a' or 'A'>
break;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.