AutosarC++17_10-A6.4.1

A switch statement shall have at least two case-clauses, distinct from the default label

Required inputs: IR

Rationale

A switch statement constructed with less than two case-clauses can be expressed as an if statement more naturally.

Note that a switch statement with no case-clauses is redundant.

Example
// $Id: A6-4-1.cpp 289436 2017-10-04 10:45:23Z michal.szczepankiewicz $
#include <cstdint>
void F1(std::uint8_t choice) noexcept {
  switch (choice) {
  default:
    break;
  } // Non-compliant, the switch statement is redundant
}
void F2(std::uint8_t choice) noexcept {
  switch (choice) {
  case 0:
    // ...
    break;

  default:
    // ...
    break;
  } // Non-compliant, only 1 case-clause

  if (choice == 0) // Compliant, an equivalent if statement
  {
    // ...
  } else {
    // ...
  }

  // ...
  switch (choice) {
  case 0:
    // ...
    break;

  case 1:
    // ...
    break;

  default:
    // ...
    break;
  } // Compliant
}
See Also
  • MISRA C++ 2008 [6]: Rule 6-4-8 Every switch statement shall have at least one case-clause.
  • HIC++ v4.0 [8]: 6.1.4 Ensure that a switch statement has at least two case labels, distinct from the default label.

Possible Messages

Key

Text

Severity

Disabled

empty_switch

Switch has no “case” clause.

None

False

minimum_switch_cases

Switch does not have enough code paths.

None

False

Options

count_default_clause

count_default_clause : bool = False

Whether a default clause should be counted.
 

minimum_switch_cases

minimum_switch_cases : int = 2

The number of clauses a switch statement should at least have. Whether a default clause is counted depends on the option count_default_clause.

Note: multiple case-labels applied to the same code block are only counted as a single switch clause.