Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a programming language with better approach for switch's break statements?

It's the same syntax in a way too many languages:

switch (someValue) {

  case OPTION_ONE:
  case OPTION_LIKE_ONE:
  case OPTION_ONE_SIMILAR:
    doSomeStuff1();
    break; // EXIT the switch

  case OPTION_TWO_WITH_PRE_ACTION:
    doPreActionStuff2();
    // the default is to CONTINUE to next case

  case OPTION_TWO:
    doSomeStuff2();
    break; // EXIT the switch

  case OPTION_THREE:
    doSomeStuff3();
    break; // EXIT the switch

}

Now, all you know that break statements are required, because the switch will continue to the next case when break statement is missing. We have an example of that with OPTION_LIKE_ONE, OPTION_ONE_SIMILAR and OPTION_TWO_WITH_PRE_ACTION. The problem is that we only need this "skip to next case" very very very rarely. And very often we put break at the end of case.

It's very easy for a beginner to forget about it. And one of my C teachers even explained it to us as if it was a bug in C language (don't want to talk about it :)

I would like to ask if there are any other languages that I don't know of (or forgot about) that handle switch/case like this:

switch (someValue) {

  case OPTION_ONE:  continue; // CONTINUE to next case
  case OPTION_LIKE_ONE:  continue; // CONTINUE to next case
  case OPTION_ONE_SIMILAR:
    doSomeStuff1();
    // the default is to EXIT the switch

  case OPTION_TWO_WITH_PRE_ACTION:
    doPreActionStuff2();
    continue; // CONTINUE to next case

  case OPTION_TWO:
    doSomeStuff2();
    // the default is to EXIT the switch

  case OPTION_THREE:
    doSomeStuff3();
    // the default is to EXIT the switch

}

The second question: is there any historical meaning to why we have the current break approach in C? Maybe continue to next case was used far more often than we use it these days ?

like image 341
m_vitaly Avatar asked Jun 10 '10 13:06

m_vitaly


1 Answers

From this article, I can enumerate some languages that don't require a break-like statement:

  1. Ada (no fallthrough)
  2. Eiffel (no fallthrough)
  3. Pascal (no fallthrough)
  4. Go - fallthrough
  5. Perl - continue
  6. Ruby (no fallthrough)
  7. VB, VBA, VBS, VB.NET (no fallthrough)
  8. To be continued by someone else...

Your second question is pretty interesting. Assuming only C, I believe this decision keeps the language cohesive. Since break is a jump, it must be explicitly written.

like image 181
jweyrich Avatar answered Oct 11 '22 11:10

jweyrich