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
Great👏
LikeLike
Thank you!!
LikeLike
Thanks
LikeLike