Main Content

AUTOSAR C++14 Rule M6-4-4

A switch-label shall only be used when the most closely-enclosing compound statement is the body of a switch statement

Description

Rule Definition

A switch-label shall only be used when the most closely-enclosing compound statement is the body of a switch statement.

Rationale

Placing a case-label or default-label of a switch statement in different scopes might result in unstructured code. Unstructured code might lead to unexpected behavior resulting in developer confusion. To prevent this issue, all case-labels and the default-label must be at the same scope of the compound statement forming the body of the switch statement.

Polyspace Implementation

Polyspace® raises this defect whenever a case-label belongs to any scope other than the switch statement body.

Troubleshooting

If you expect a rule violation but Polyspace does not report it, see Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

#include <cstdint>

int y, sum;

int heresASum(int a, int b)
{
    sum = a + b;
    return sum;
}

int example(int x)
{
    switch (x) {
    case 1:                          //compliant
        if (y > 0) {
        case 2:                      //noncompliant
            y = heresASum(x, y);
            break;
        }
        break;

    case 3:
        break;

    default:
        break;
    }
	
	return x;
}

Because the case-label case 2 in nested under the case 1 case-label, it is considered in a different scope from the other case-label statements and the default-label statement. All of these other case-label statements are in the same scope of the body of the switch-label statement.

Check Information

Group: Statements
Category: Required, Automated

Version History

Introduced in R2019a