C / C ++条件return语句 [英] C/C++ conditional return statements

查看:318
本文介绍了C / C ++条件return语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我工作的嵌入式程序,在某些情况下,如果一个条件是不是意味着,我想从功能迅速恢复越好。如果我有以下的code和我做嵌入式编程:

I am working on embedded program and in certain cases if a condition is not meant, I would like to return from function as quickly as possible. if I have the following code and I am doing embedded programming:

foo() {
   if (a < b) {
       return 0;  // bail, since condition is met
   } else {
       // lots of calculations in this block
   }
   return 1;
}

我的问题是,这样做不好有多个return语句?它是不好的做法?有没有更好的方法呢?是否MISRA说什么?

My question is, is it bad having multiple return statements? Is it bad practice? Are there better methods? Does MISRA say anything about it?

请注意:这个问题特别是嵌入式系统,与MISRA做的不只是C / C ++

NOTE: This question is particular to Embedded Systems, has to do with MISRA not just C/C++

谢谢...

推荐答案

MISRA需要一个return语句:

MISRA requires a single return statement:

(MISRA,规则14.7:必填)

(MISRA, rule 14.7 : required) "A function shall have a single point of exit at the end of the function"

现在,我个人不认为这是一个很好的规则。最小化return语句的数量,但使用return语句时,它增强你的code的可读性。

Now, personally I don't think it is a good rule. Minimize the number of return statements but use a return statement when it enhances the readability of your code.

例如后卫条款可以让你的code更清洁,更具有可读性。

For example guard clauses can make your code cleaner and more readable.

我建议你阅读这篇文章了解达芬(写入code从上到下):

I suggest you to read this article about duffing (writing code from top to bottom):

这篇关于C / C ++条件return语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆