Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return vs break when closing a function?

Tags:

c++

for-loop

Say I have a single-for loop function; would it be best to choose return or break if there is no mechanic-related preference to it? Or they would be exactly the same?

void function()
{
  for (int i; i<foo; i++)
     {
         if (something)
            // return? break?
     }
  // nothing else after this
}
like image 369
Banderi Avatar asked Jun 18 '26 15:06

Banderi


1 Answers

Using break will quit the loop, whereas return will actually complete the method. So if your goal is to simply stop the loop, you can use break. However, if you want the method to end, use return. See this post for some additional comments on special cases of return vs breaks: break and return in ruby, how do you use them?

********EDIT******** In this scenario, they will work exactly the same, unless you have more code under the for loop in the function. If that is the case, use break to hit that code.

like image 192
bmac151 Avatar answered Jun 21 '26 20:06

bmac151



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!