2

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
}
Banderi
  • 656
  • 3
  • 7
  • 29

3 Answers3

6

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.

Community
  • 1
  • 1
bmac151
  • 505
  • 3
  • 8
  • Yeah, the point is they do the same in this case. I guess they do the exact same thing here – Banderi Aug 24 '13 at 20:11
  • @Banderi Zealots about single-return points in functions will tell you use `break` regardless. Honestly, just make it clear what is going on to anyone (including yourself) that is reading this code later. – WhozCraig Aug 24 '13 at 20:13
  • Yeah, I would say break in this case may imply that other code is to come. If you have no other code below the loop, I would use return. – bmac151 Aug 24 '13 at 20:14
3

In terms of code generated you can expect them to be exactly the same in this scenario.

However, return has a different meaning than break. Return means you're exiting the function while break just exits the loop. The result might be the same now, but that may change when algorithm changes or when you need to do some post-processing, for example.

What's more appropriate in this scenario is impossible to say without the actual code, and even then might depend on opinion.

orlp
  • 112,504
  • 36
  • 218
  • 315
  • Yeah, it was kind of a more general question. Since ending either works fine for me, and they also end each-other, I guess they're the same deal. – Banderi Aug 24 '13 at 20:14
  • @Banderi I tried (and apparently failed) to point out in my answer that they are __not__ the same deal, there is a subtle difference - even in this scenario. – orlp Aug 24 '13 at 20:18
  • Well, the only thing I need to do is end the function, so their difference in this case would seem to be either preference or what I would have to do with the function later on.. I guess? I know what they "actually" mean, though – Banderi Aug 24 '13 at 20:21
1

I'd prefer to use a break in this situation. Requirements can change over time, and someday you might have to add another piece of code after the loop. Then, the early return might be a bug waiting to happen, especially if the early loop exit is for a rare and hard to test condition.

Jim Lewis
  • 43,505
  • 7
  • 82
  • 96