Search code examples
creturntime-complexity

Need to know good practice should i follow on below code


i have code as :

 int good_practice(void)
    {
      if (somethings == TRUE)
       return true;  //i am asked to remove it coz it will reach anyhow at end and do same but i feels it is good practice and why should i wait for end?
      else
       return false
      }
     }
     return true; 
    }

i am asked remove first return since it will ultimately reach end of function and will return true.Is this good ?

what i feel why do i need to wait for cpu to go at end of function and return though i can do early.if i have decide to return with some condition why should i return from end why not there itself why to wait for end ?

And also if i am wait for end the i increase time complexity(i know it won't make any difference) but no of instruction is also increased.

please help me to get out of this confusion?


Solution

  • This is called an “early return” and I don’t think there is a clear consensus.

    Pros:

    • You can’t execute some other code by mistake if you return early.
    • If you are reading this particular execution branch, the early return makes the flow more explicit.
    • It’s also possible to decrease the indent level by returning early.

    Cons:

    • When you’re looking at the whole function, it’s easier to miss an early return.

    There are some similar previous questions about early returns, see here for example.