c 中的 Switch-case:从另一个 case 继续到 'default'

Switch-case in c: continue to 'default' from within another case

有没有办法开始处理案件,并在中间(不是结尾)继续运行 'default' .我看到我可以删除 'break',但它会在结束整个当前案例后继续下一个案例。 示例:

switch( X ) 
{
    case 'A':
        // Start this code
        if (expression){
            // Go to execute 'default'
        }
        // Don't run this if the expression is true
    case 'B':
            // code..
    default :
            // code..
}

(寻找解决方案,而不是将 'default' 设为函数并从案例中调用它)

您可以使用标签:

goto default2;

如果你输入:

default2:

在默认值旁边

你能做的最好的(因为你不想在函数中使用默认代码)是将默认代码放在开关之后,并在你想要默认代码时设置一个标志 运行 .

int runDefault = false;

switch( X ) 
{
    case 'A':
        // Start this code
        if (expression){
            runDefault = true;
            break;
        }
        // This code doesn't run this if the expression is true
        break;

    case 'B':
        // code..
        break;

    default :
        runDefault = true;
        break;
}

if ( runDefault )
{
    // default code goes here
}

case 语句不必按顺序排列。

switch( X ) 
{
    case 'B':
        // code..
        break;
    case 'A':
        // code..
        if (!expression){
            // code
            break;
        }
        // code..
        // Fall thru
    default :
        // code..
}

这去除了丑陋的东西goto

Is there a way to start handling a case, and in the middle (not end) of it to move on to run the 'default'.

是一种方法,如 geocar 的正确简洁答案中所述。但是您还应该考虑是否 应该 使用 goto 通过 switch 语句修改执行流程。这不是大多数人希望看到的东西,并且对于避免以令人惊讶的方式工作的代码有很多话要说。 如果您决定按照您的建议进行,请附上评论,解释正在发生的事情以及您这样做的原因。

看来最好在案例 B 中使用标志检查来处理这个问题,并让下降正常进行。任何其他想要避免默认的情况都会在情况 A 之前进行并暂停。

查看问题中的代码,您似乎想让案例 A 都落入案例 B(并检查表达式),然后让案例 B 落入默认值,以便在中执行默认值所有情况。您似乎也不想更改开关以将默认值移到开关之外(最小更改)。

int myflag = FALSE;
switch( X ) 
{
  case 'A':
  {
    // Start this code
    if (expression){
        myflag = TRUE;
        // Now the fall through would go to default
    }
  }
    // Don't run this if the expression is true
  case 'B':
    {
        if (! myflag) {
          // code..
        }
    }
  default :
        // code..
}