替代开关案例返回
我想在开关案例中返回一些东西。但是,使用交换机中的回报违反了Misra规则6-4-3,因此我正在寻找替代方案。
规则说:开关语句应为一个良好的开关语句。返回语句不得在开关条款中使用。
代码:
switch(x) {
case 0:
doSomething();
break;
case 1:
return true; // violates MISRA 6-4-3
case 2:
doSomething();
break;
default:
doSomething();
break;
}
我知道它可以通过这种方式解决:
bool var = false;
switch(x) {
case 0:
doSomething();
break;
case 1:
var = true;
break;
case 2:
doSomething();
break;
default:
doSomething();
break;
}
return var;
但是如果可能的话,我想在没有其他代码的情况下解决它。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
阅读 misra c ++ 2008标准,没有任何地方说:
但是,它确实说:
因此,无论如何,您都无法在
case
内使用返回
。您别无选择,只能使用本地变量来记住case
想要返回的值,然后在功能结束时在最终return
中使用该变量。Reading Misra C++ 2008 Standards, nowhere does it say:
But, it does say:
So, you couldn't use a
return
inside acase
anyway. You have no choice but to use a local variable to remember the value thecase
wants to return, and then use that variable in the finalreturn
at the end of the function.目前尚不清楚该功能中是否有更多代码。
但要做这样的事情是一个简单的事情:
It's not clear if you have more code in the function.
But it's a simple matter to do something like this:
Misras的多个
返回
规则已进行了很多辩论(在此和其他地方)。但是,如果我们跳过该规则的细节和switch
格式规则,那么这些规则的本质都归结为“不必为其付出不必要的复杂/意大利面条代码”。这就是您在这里做的。编写陌生人代码也不是解决方案。您应该做的是抛弃这整个奇怪的
switch
语句,倾向于更明智的事物,例如:这可能不符合Misra,但在常识上是综合的。剩下的任何MISRA警告都可能是由于咨询规则,在这种情况下,您可以忽略它们。
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 theswitch
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: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.