>
>
>
V2520. MISRA. Every switch-clause shoul…


V2520. MISRA. Every switch-clause should be terminated by an unconditional 'break' or 'throw' statement.

This diagnostic rule is based on the software development guidelines developed by MISRA (Motor Industry Software Reliability Association).

This diagnostic varies for C and C++. Each label of a 'switch' statement should end with a 'break' statement placed outside the condition. In C++, 'throw' can also be the last statement.

Adding the ending statements guarantees that the execution flow will not "fall through" to the next label and also helps avoid mistakes when adding new labels.

The only exception to this rule is a series of empty labels.

Here is an example of code triggering this warning:

void example_1(int cond, int a)
{
  switch (cond)
  {
  case 1:
  case 2:
    break;
  case 3:  // <=
    if (a == 42)
    {
      DoSmth();
    }
  case 4:  // <=
    DoSmth2();
  default: // <=
    ;
  }
}

Fixed code:

void example_1(int cond, int a)
{
  switch (cond)
  {
  case 1:
  case 2:
    break;
  case 3:
    if (a == 42)
    {
       DoSmth();
    }
    break;
  case 4:
    DoSmth2();
    break;
  default:
    /* No action required */ 
    break;
  }
}

Note that labels should not end with a 'return' statement as it violates the rule V2506.

This diagnostic is classified as:

  • MISRA-C-16.3
  • MISRA-CPP-6.4.5