Should the switch statement exist?

One of the more controversial things about some new languages such as Julia, Python and Lua is that they have done away with the switch/case statement. Some see this as a limitation of the language, but others, like myself see it as evolution, similar to the human body spurning the appendix – may have been a good idea once, but is it even needed anymore. It would be one thing if the functionality of the language was seriously impacted, but in languages such as C, the switch statement is often more of a burden than anything else. Switch and its brethren evolved from the select-when statement of PL/I in the mid 1960s. Its structure looked like this:

    when (C1) S1;
    when (C2) S2;
    when (C3) S3;
    otherwise S4;

This was likely easier to interpret than it’s modern rendition. But as time progressed, the case statements evolved into complex beings, with the most handicapped form likely being that of C.

In essence, anything a switch/case statement can do can be achieved using a standard if-else statement, especially if the statement incorporates the shortcut elseif (of elif, elsif etc). The issue for novices programmers of course is “Why should I use the switch statement”, or “Is switch better?”. It is hard to answer these questions. For novice programmers, the use of a structure which in effect performs the same function as another is confusing. Never mind implicit fall-through.

So leaving out the switch statement in a language is not a bad idea, especially from a simplicity point-of-view.


The other trick is that in C there is no clear way of deriving a switch statement from:

if (x > 0)
else if (x < 0)

This occurs largely because there is only one branch of this statement with a distinct  value, the last one where x equals zero. Positive numbers go from 1 to infinity, so naturally you see the problem (Is zero positive? that’s likely a philosophical question). Languages such as Swift have taken another approach and modified the switch statement to allow multiple cases on the same line, or ranges. Still doesn’t solve the above problem. But then again having a structure like this:

    when (x>0) print(“positive”)
    when (x<0) print(“negative”)
    otherwise  print(“zero”)

May be all but redundant with the existence of if.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s