KplnMoon
KplnMoon

Reputation: 159

Alternative to return in switch-cases

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.

Upvotes: -1

Views: 1493

Answers (3)

Lundin
Lundin

Reputation: 214780

The multiple return rule of the MISRAs has been debated a lot (here on SO and elsewhere). However, if we skip the specifics of that rule and the switch format rule, the essence of those rules all boil down to "do not write needlessly complex/spaghetti code just for the heck of it". Which is what you are doing here. Writing even stranger code is not the solution.

What you should do is to ditch this whole strange switch statement in favour of something more sensible, such as this:

if(x == 1) // comment explaining why this is a special case
{
  return true;
}

doSomething();

This may not conform to MISRA but it comforms to common sense. Any MISRA warnings remaining are likely because of advisory rules, in which case you can ignore them.

Upvotes: 1

Remy Lebeau
Remy Lebeau

Reputation: 597941

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.

Upvotes: 3

Jonathan Wood
Jonathan Wood

Reputation: 67335

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;

Upvotes: 2

Related Questions