>
>
>
V2527. MISRA. A switch-expression shoul…


V2527. MISRA. A switch-expression should not have Boolean type. Consider using of 'if-else' construct.

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

A Boolean value can be cast to an integer and, therefore, can be used as a control variable in a 'switch' statement. However, it is preferable to use an 'if-else' construct in such cases as it conveys the developer's intentions in a clearer and more explicit way.

Original code:

int foo(unsigned a, unsigned b)
{
  while (a != 0 && b != 0)
  {
    switch (a > b) // <=
    {
    case 0:
      a -= b;
      break;
    default:
      b -= a;
      break;
    }
  }
  return a;
}

Better version:

int foo(unsigned a, unsigned b)
{
  while (a != 0 && b != 0)
  {
    if (a > b)
    {
      b -= a;
    }
    else
    {
      a -= b;
    }
  }
  return a;
}

This diagnostic is classified as:

  • MISRA-C-16.7
  • MISRA-CPP-6.4.7