switch(ch){
case \'a\':
//do something, condition does not match so go to default case
//don\'t break in here, and don\'t
If you must have the switch statements first because the condition you're checking for depends on the case (or the case has to be evaluated first before you can check on the condition), simply set a flag inside your switch
cases, and if that flag is set, then do a default operation. For instance:
int default_true = 0;
switch (case_value)
{
case 'a': /* if the condition is true, set the default_true flag */
case 'b': /* if the condition is true, set the default_true flag */
//...
default: default_flag = 1; // set the default_true flag to true
}
if (default_flag)
{
//place your "default" code here rather than inside the switch statement
//this prevents code reduplication
}
I hope my solution answers your question. Simply let the cases follow through all the way (beginning with the matching case) but use a condition to disable subsequent cases from running.
typedef enum boolean
{
FALSE = 0, TRUE = 1
} bool;
void pstuff(char input)
{
bool _skip = FALSE;
switch(input)
{
case 'a':
printf("Case a.");
_skip = TRUE;
case 'b':
if(!_skip)
{
printf("Case b.");
_skip = TRUE;
}
case 'c':
if(!_skip)
{
printf("Case c.");
_skip = TRUE;
}
//...
default:
printf("Done!\n"); //Always gets printed.
}
}
If the condition doesn't depend on cases, why put it inside?
if (!condition){
// do default
}else{
switch(ch){
case 'a':
// do a
break;
...
}
}