Home > database >  Alternative to return in switch-cases
Alternative to return in switch-cases

Time:05-16

I want to return something in a switch-case. However, using a return in a switch-case violates MISRA rule 6-4-3, so I'm looking for an alternative.

The rule says: A switch statement shall be a well-formed switch statement. Return statements shall not be used in switch clauses.

Code:

switch(x) {
  case 0:
   doSomething();
   break;
  case 1:
   return true; // violates MISRA 6-4-3
  case 2:
   doSomething();
   break;
  default:
   doSomething();
   break;
}

I know that it can be solved this way:

bool var = false;
switch(x) {
  case 0:
   doSomething();
   break;
  case 1:
   var = true;
   break;
  case 2:
   doSomething();
   break;
  default:
   doSomething();
   break;
}
return var;

But I would like to solve it without additional code if it is possible.

CodePudding user response:

Reading Misra C 2008 Standards, nowhere does it say:

Return statements shall not be used in switch clauses.

But, it does say:

A function shall have a single point of exit at the end of the function

So, you couldn't use a return inside a case anyway. You have no choice but to use a local variable to remember the value the case wants to return, and then use that variable in the final return at the end of the function.

CodePudding user response:

It's not clear if you have more code in the function.

But it's a simple matter to do something like this:

bool abort = false;
switch(x) {
  case 0:
   doSomething();
   break;
  case 1:
   abort = true;
   break;
  case 2:
   doSomething();
   break;
  default:
   doSomething();
   break;
}

if (abort)
  return true;
  • Related