在switch语句中从一个case跳转到默认大小写

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)

  • 但是,如果你写意大利面条代码,你会被闪电击中的规则如何:p? (6认同)
  • @pmg,哈哈,非常可怕.我用谷歌搜索"javascript switch goto",这是第二次点击.在我的疏忽中,我没有意识到这个问题与Javascript无关. (5认同)

Die*_*lla 7

只需重新排序案例,以便最后一个案例:

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)

  • 啊,所有案件都要表现得一样吗?然后,你必须更多地解释你的问题,因为,例如,条件取决于案件的价值? (2认同)

mou*_*iel 5

如果病情不依赖于病例,为什么要把它放进去?

if (!condition){
  // do default
}else{
  switch(ch){
    case 'a':
      // do a
      break;
    ...
  }
}
Run Code Online (Sandbox Code Playgroud)


Kao*_*aos 5

重构你的代码:

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语句中.