No fall-through for switch (WAS: Re: [Submission] D Slices)

Andrei Alexandrescu SeeWebsiteForEmail at erdani.org
Tue May 31 14:43:19 PDT 2011


On 5/31/11 4:37 PM, Andrej Mitrovic wrote:
> As for switch statements (and this is getting offtopic), there are
> cases where fallback is nice to have..
>
> final switch (param)
> {
>      case FILE_NEW:
>      case FILE_OPEN:
>      case FILE_SAVE:
>      case FILE_SAVE_AS:
>      case EDIT_UNDO:
>          throw new Exception("unimplemented!");  // or there would be
> one method that handles these cases
>      case EDIT_CUT:
>          handleCut();
>          break;
>      case EDIT_COPY:
>          handleCopy();
>          break;
>      case EDIT_PASTE:
>          handlePaste();
>          break;
>      case EDIT_CLEAR:
>          handleClear();
>          break;
> }
> return 0;
>
> If you didn't have fallback, you would probably have to add some kind
> of new statement like "goto next" or "fallback" on each of those
> cases.

Currently the best proposed behavior is to only require control flow if 
there is actual code before it. So adjacent case labels don't require 
any. Your example code would work unmodified.

For the rare cases where fall-through is actually needed, goto case xxx; 
has been proposed. It has the advantage that it's robust to reordering 
of labels, and the disadvantage that it's not robust to swapping label 
names. Arguably, such swapping is an infrequent refactoring.


Andrei


More information about the Digitalmars-d mailing list