Since programming language is abstract, the best way to understand it is by using an analogy.
Today, I want to explain the concept of switch-case as an alternative to if-else in a possible plain using, of course, an analogy.
Case study (pun intended)
Imagine that you have an electrical circuit with different outputs. Each output is inside its respective
case with a unique connector shape and equipped with an indicator light that will turn on when in use.
Now, whenever you want to operate a certain case, you must pair it with a perfectly similar connector. Should they are matched, the indicator runs and the rest of the cases are ignored. Or to put it simply, you can decide which one to switch on.
What a cool idea, huh?
Now let’s take a look at a simple electrical circuit below:
Let’s say that you want to turn on the indicator for the rectangle connector. What will you do? Yes, you use the pin with a similar rectangle shape to the connector.
The indicator will turn on and the brake is activated, ignoring the rest of the connector. If you change the pin with the diamond shape, it won’t turn on the rectangle indicator since they are no match. What it will do is now finding the next match — in this case, the diamond connector:
The same thing happens if we change the pin with an octagon shape:
But, what if there is no match found? Isn’t it will make the system fail? Fret not! Enter the default case (or just
default). Think of default as a universal connector that will adjust its shape to match whatever the switch when it can’t find its match.
Since the default state is the last checkpoint, it won’t have
Putting It All Together and Final Thought
Pretty much the same right?
Hope this story gives you the plain understanding of