I'm currently learning the basics in C programming and was about to try out the switch-statement. 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.
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. 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'
is evaluated as a boolean, which returns 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 '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.
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. You have two options here:
1) Using fall through
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. For example:
switch (tolower(answer))
{
case 'a':
<code for 'a' or 'A'>
break;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.