C/C++ conditional return statements

user1135541 picture user1135541 · Jun 18, 2013 · Viewed 10.6k times · Source

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...

Answer

ouah picture ouah · Jun 18, 2013

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):