Switching Things Up
If you have ever used a switch statement in MATLAB and also used it in C, you might have noticed that the two constructs have different semantics.
switch in C
In C, you often terminate case statements in switch constructs with a break statement to prevent execution of the code in the case that follows. Omitting the break statement causes the code in the following case to execute. The behavior of switch statements in C is sometimes described as fall through.
switch in MATLAB
There are several major differences between switch statements in MATLAB and C.
More on switch in MATLAB
When we originally were designing switch for MATLAB, we examined much of our own C source code, and we found a huge majority of the case statements terminated in break, hence the no fall-through behavior of MATLAB. This makes the switch statement in MATLAB equivalent to an if-elseif construct. To achieve fall-through behavior in MATLAB, you can specify all the relevant expressions in one case and then conditionally compute values within that section of code.
Do You Use switch Statements?
I am curious to hear about your experiences using switch statements in MATLAB. Post your thoughts here.
To leave a comment, please click here to sign in to your MathWorks Account or create a new one.