Programming: Switch Statements

Something interesting I have figured out while working on embedded C. Diving straight to my point, what is the best way to implement this code using switch case.

Implementation with if-else:

uint8_t choice = 2;

if(choice==1||choice==2||choice==3)
{
    function1();
}
else
{
    function2();
}

Most probably the efficient way to implement this is still in if-else, but from a purely academic and hobby point of view, how would you do this. Or is this even possible? The most straight forward solution to this would be:

Implementation 1 with switch case:

uint8_t choice = 2;

switch(choice):
{
    case 1: function1();
        break;
    case 2: function1();
        break;
    case 3: function1();
        break;
    default: function2():
        break;
}

This of-course works, but can we make it even more concise. This is where the concept of fall-through comes. If we do not have the break statement between consecutive case statements, the execution falls to the adjacent case after executing the present case. Implementing an even concise version of the code.

Implementation 1 with switch case:

uint8_t choice = 2;

switch(choice):
{
    case 1: 
    case 2: 
    case 3: function1();
        break;
    default: function2():
        break;
}

Here the default statement is equivalent to the else. Since break conditions are not present the flow execution falls through from case1 to case 2 to case 3.

This is just to show how fall through can be useful in switch case. I do not have any metric if this implementation has any significant memory or time saving over the if-else construct. In case you want to read something more on switch cases, check this blog I found on the web: Be wary of switch statements

3 thoughts on “Programming: Switch Statements

Add yours

Leave a Reply

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

WordPress.com Logo

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

Google photo

You are commenting using your Google 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 )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Powered by WordPress.com.

Up ↑

Create your website at WordPress.com
Get started
%d bloggers like this: