Switch statement: must default be the last case?

后端 未结 10 2125
面向向阳花
面向向阳花 2020-11-27 02:36

Consider the following switch statement:

switch( value )
{
  case 1:
    return 1;
  default:
    value++;
    // fall-through
  case 2:
    ret         


        
10条回答
  •  感情败类
    2020-11-27 03:11

    One scenario where I would consider it appropriate to have a 'default' located somewhere other than the end of a case statement is in a state machine where an invalid state should reset the machine and proceed as though it were the initial state. For example:

    switch(widget_state)
    {
      default:  /* Fell off the rails--reset and continue */
        widget_state = WIDGET_START;
        /* Fall through */
      case WIDGET_START:
        ...
        break;
      case WIDGET_WHATEVER:
        ...
        break;
    }
    

    an alternative arrangement, if an invalid state should not reset the machine but should be readily identifiable as an invalid state:

    switch(widget_state) { case WIDGET_IDLE: widget_ready = 0; widget_hardware_off(); break; case WIDGET_START: ... break; case WIDGET_WHATEVER: ... break; default: widget_state = WIDGET_INVALID_STATE; /* Fall through */ case WIDGET_INVALID_STATE: widget_ready = 0; widget_hardware_off(); ... do whatever else is necessary to establish a "safe" condition }

    Code elsewhere may then check for (widget_state == WIDGET_INVALID_STATE) and provide whatever error-reporting or state-reset behavior seems appropriate. For example, the status-bar code could show an error icon, and the "start widget" menu option which is disabled in most non-idle states could be enabled for WIDGET_INVALID_STATE as well as WIDGET_IDLE.

提交回复
热议问题