the*_*ux4 19 c break switch-statement
switch(ch){
case 'a':
//do something, condition does not match so go to default case
//don't break in here, and don't allow fall through to other cases.
case 'b':
//..
case 'c':
//..
case '_':
//...
default:
//
break;
}
Run Code Online (Sandbox Code Playgroud)
在上面的switch语句中,我输入case'a',只有当它内部的条件发生时才会中断,否则我想跳转到默认情况.有没有其他方式这样做而不是标签或者gotos?
pmg*_*pmg 23
goto 为了胜利
switch (ch) {
case 'a':
if (1) goto LINE96532;
break;
case 'b':
if (1) goto LINE96532;
break;
LINE96532:
default:
//
break;
}
Run Code Online (Sandbox Code Playgroud)
只需重新排序案例,以便最后一个案例:
switch(ch){
case 'b':
//..
case 'c':
//..
case '_':
//...
case 'a':
//do something, condition does not match so go to default case
if (condition)
break;
//don't break in here, and don't allow fall through to other cases.
default:
//
break;
}
Run Code Online (Sandbox Code Playgroud)
如果病情不依赖于病例,为什么要把它放进去?
if (!condition){
// do default
}else{
switch(ch){
case 'a':
// do a
break;
...
}
}
Run Code Online (Sandbox Code Playgroud)
重构你的代码:
int test_char(char ch)
{
switch(ch) {
case 'a': if (condition) return 0; break;
case 'b': // ...
default: return -1;
}
return 1;
}
...
// defaults processing switch
switch(test_char(ch)) {
case 0: break; // condition met
case 1: // default processing
default: // case not handled by test_char
}
Run Code Online (Sandbox Code Playgroud)
这还增加了灵活地测试多类默认处理的好处.假设你有一组共享一些常见逻辑的字符[c,d,e,f].对于这些情况(可能在测试了一些条件之后),只需从test_char()返回2,并将case 2:handler添加到缺省处理switch语句中.