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;
}
My question is, is it bad having multiple return statements? Is it bad practice? Are there better methods? Does MISRA say anything about it?
NOTE: This question is particular to Embedded Systems, has to do with MISRA not just C/C++
Thanks...
Well, they work as return statements. Of course it only make sense to have one return statement for each code path in your function. Show activity on this post. If there are returns in other logic blocks.. then you could conceivably have multiple returns in a function.
You cannot conditionally return from the middle of an expression, because return is a statement, you have to return the whole expression.
The ternary operator takes 3 operands (condition, expression1 and expression2) . Hence, the name ternary operator.
MISRA requires a single return statement:
(MISRA, rule 14.7 : required) "A function shall have a single point of exit at the end of the function"
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.
For example guard clauses can make your code cleaner and more readable.
I suggest you to read this article about duffing (writing code from top to bottom):
I would have written that like so because the else
is redundant:
if (a < b) {
return 0; // bail, since condition is met
}
// lots of calculations in this block
return 1;
I don't think there's a rule of thumb, but if the function is really long and you have multiple return points, it can be hard to maintain and understand.
However, in a recursive function, for example, it's very handy to put your "base cases" as return statements at the beginning of a function.
For example, consider factorial:
int fact(int x) {
// base cases
if (x == 0 || x == 1)
return 1;
// recursive call
return x * fact(x-1);
}
You could also write it like this:
int fact(int x) {
int ret = 0;
if (x == 0 || x == 1)
ret = 1;
else
ret = x * fact(x-1);
return ret;
}
I just like the first way better, but it doesn't mean either way is better than the other.
It really comes down to whatever standards you must follow and personal preference.
Some consider it bad practice, I'm personally ok with it as it can be cleaner-looking code. You can also do it in this way:
foo() {
int results = 0; // good practice to initialize
if (a < b) {
results = 0; // redundant, likely optimized out
} else {
// lots of calculations in this block
results = 1;
}
return results;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With