Main Content

MISRA C:2023 Rule 16.5

A default label shall appear as either the first or the last switch label of a switch statement

Since R2024a

Description

Rule Definition

A default label shall appear as either the first or the last switch label of a switch statement.

Rationale

Using this rule, you can easily locate the default label within a switch statement.

Troubleshooting

If you expect a rule violation but do not see it, refer to Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

void foo(int var){

    switch(var){
        default:   /* Compliant - default is the first label */
        case 0:
            ++var;
            break;
        case 1:
        case 2:
            break;
    }
        
    switch(var){
        case 0:
            ++var;
            break;
        default:    /* Non-compliant - default is mixed with the case labels */
        case 1:
        case 2:
            break;
    }
    
    switch(var){
        case 0:
            ++var;
            break;
        case 1:
        case 2:
        default:     /* Compliant - default is the last label */
            break;
    }
    
    switch(var){
        case 0:
            ++var;
            break;
        case 1:
        case 2:
            break;
        default:      /* Compliant - default is the last label */
            var = 0;
            break;
    }
}

This example shows the same switch statement several times, each with default in a different place. As the first, third, and fourth switch statements show, default must be the first or last label. default can be part of a compound switch-clause (for instance, the third switch example), but it must be the last listed.

Check Information

Group: Switch Statements
Category: Required
AGC Category: Advisory

Version History

Introduced in R2024a