Main Content

na_0022: Recommended patterns for Switch/Case statements

Since R2020a

Guideline Publication

Control Algorithm Modeling Guidelines - Using MATLAB®, Simulink®, and Stateflow®

Sub ID Recommendations

  • NA-MAAB — a

  • JMAAB — Not supported

MATLAB Versions

All

Rule

Sub ID a

Switch/Case statements shall use constant values for Case arguments.

Input variables shall not be used in Case arguments.

Custom Parameter

Not Applicable

Example — Correct
function outVar = NA_0022_Pass(SwitchVar)
%#codegen
    switch SwitchVar
        case Case_1_Parameter % Parameter
            outVar = 0;
        case NA_0022.Case_2 % Enumerated Data Type    
            outVar = 2;
        otherwise
            outVar = 10;
    end
end
Example — Incorrect
function outVar = NA_0022_Fail(Case_1,Case_2,Case_3,SwitchVar)
%#codegen
    switch SwitchVar
        case Case_1
            outVar = 1;
        case Case_2
            outVar = 2;
        case Case_3
            outVar = 3;
        otherwise
            outVar = 10;
    end
end

Rationale

Sub ID a:

  • Improves model simulation and testability.

  • Code generation may not be possible.

Verification

Model Advisor check: Check usage of recommended patterns for Switch/Case statements (Simulink Check)

Last Changed

R2020a

Version History

Introduced in R2020a