-
Merging Case Functions
Instead of this:
Code:
case 'r':
{ Mufftastic code. }
case 'R':
{ Same mufftastic code. }
I need something that combines them, like this (even though this code doesn't work):
Code:
case 'r' || 'R':
{ Mufftastic code. }
Can anyone offer any advice? Examples, even? Thanks!
-
Code:
case 'r' :
case 'R' :
//insert code here
break;
-
There is such a thing as "fallthrough":
Code:
case 'r':
/* Nothing here, so we "fall through" to the next case */
case 'R':
/* Code. */
Which is why break is so important in cases, normally.
-
Or you could even do
Code:
switch ( toupper(ch) ) {
case 'R': // also case 'r' from the toupper() in the switch
}
Consider this, if you have a lot of case letters to choose from. A missing fall-through case would be a hard bug to spot in a sea of other cases.
But if you also have
Code:
switch ( monty ) {
case 'X': // do something
case 'x': // and now for something completely different
}
then you will need to use the fall through style for any letters where case does not matter.
-
I never did think about doing such a thing. Thanks, everyone! :D
-
If you want a little fun with switch case, to illustrate the issue...
Code:
#include <stdio.h>
int main (void)
{
int i;
for (i = 0; i < 5; i ++)
{
switch(i)
{
case 0 :
printf("The ");
case 1 :
printf("fast ");
case 2:
printf("feline ");
case 3:
printf("flies ");
case 4:
printf("farthest");
case 5:
printf("\n");
}
printf "\n");
}
return 0;
}