Main Content

MISRA C++:2008 Rule 6-4-6

The final clause of a switch statement shall be the default-clause

Description

Rule Definition

The final clause of a switch statement shall be the default-clause.

Rationale

It is a good defensive programming technique to always use a default clause as the final clause of a switch statement. The default clause must either take appropriate action or contain a comment as to why the default clause takes no action.

Polyspace Implementation

The rule checker detects switch statements that do not have a final default clause.

The rule checker does not report a violation if the switch variable is an enumeration with finite number of values and you have a case clause for each value. For instance:

enum Colors { RED, BLUE, YELLOW } color;

switch (color) {
      case RED:
        break;
      case BLUE:
        break;
      case YELLOW:
        break;
}

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

Polyspace flags both switch statements in this example as noncompliant.

  • switch (i) contains multiple case statements. However, there is no default clause to handle cases where i is any value other than 0, 1, or 2. Even if i can only be 0, 1, or 2, using a default clause is defensive programming to catch any circumstance where i is unexpectedly a different value.

  • switch (colors) uses an enumeration for the switch variable. However, each value does not have an associated case clause. Adding the case clause for case BLUE makes this switch statement compliant.

#include <cstdint>

int main(){
	int i;
	//...
	switch (i)		//Noncompliant
	{
	case 0:
		break;
	case 1:
	case 2:
		break;
	}

	enum Colors { RED, BLUE, YELLOW } colors;

	switch (colors) {	//Noncompliant
	case RED:
		break;
	case YELLOW:
		break;
	}
	
	return 0;
}

Check Information

Group: Statements
Category: Required

Version History

Introduced in R2013b