#### Archived

This topic is now archived and is closed to further replies.

# "Returning" in middle of loop bad practice?

This topic is 6248 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Just wondering, is it bad practice to "return" in the middle of a loop in a function like this (I've only coded it like I have to show you what I mean). You can see that the first 'return' affects the code flow so that the function quits immediately upon obtaining an answer - is it o.k. to do that in the middle of the while loop (which has not finished)? // check if integer is less than ten bool IntLessThanTen(int intin) { int count = 0; while (count < 10) { if (intin == count) { return 1; // see here } count++; } return 0; } // end IntLessThanTen Paulcoz. Edited by - paulcoz on January 10, 2001 6:35:58 PM

##### Share on other sites
Well, that is a horrible example (it wouldn''t even work with negative numbers), but you know that...

There was some debate over that recently. I''m on the side that says immediate returns are fine. You''ll probably find someone who will disagree, somewhere, but most probably agree with me in this case.

##### Share on other sites
If what you''re asking is if this sort of thing is acceptable, sure.

  someclass& MYCLASS::FindInstance(someval what){ someclass result; for (int i=0; i

But I personally prefer this method... Just a preference I suppose.

  someclass& MYCLASS::FindInstance(someval what){ someclass result; for (int i=0; i

Regards,
Jumpster

##### Share on other sites
I think the second case is just silly! but as said it's preference.

I think it's better to explicitly call the return as soon as you can. The return sticks out (thanks to color) hence it is easier to locate return paths. If you use an acculator (result), you have not changed the logic of code whatsoever, you have simply changed the color of the word - and made it harder to locate.

The 'one way in, one way out' idea is a load of goulash. The code really doesn't work that way, the design doesn't work that way, and more importantly the RL problems you're solving don't work that way...

People that insist on results, also seem to insist on flowcharts The flowcharts themselves show the non-linearity of the problem.

Perhaps I missed something about the 1-1 idea, but as I understand it, it's not accurate.

...
I thought of a number of cases where I use accumulators. If you're initializing something, and progress through a series of nested if's, you would probably only want one return(hr) at the end.
At the same time, the code may be clearer if you did call an explicit return on an error condition right after each step of the initialization (then you wouldn't need that overly nested if block).
It's hard to say which is better, because they both suck. Is there a better way?
Magmai Kai Holmlor
- The disgruntled & disillusioned

Edited by - Magmai Kai Holmlor on January 10, 2001 9:11:44 PM

Edited by - Magmai Kai Holmlor on January 10, 2001 9:12:55 PM

##### Share on other sites

I go with whatever makes sense. I did try to follow the only 1 return in a function rule, but in many cases it simply did not make sense, resulting in messing and bug prone code. If the function''s nature is such that it makes sense to exit in the middle of a loop, then go for it. If you are initializing something like DirectX, you are probably better off with 1 return for whole function (that way you can keep your error handling and stuff straight). Unlike the dreaded GOTO, a return in the middle of the code isn''t as likely to cause memory cleaning up problems AS LONG AS you don''t do anyting too silly and keep your code neat. Hope that helps.

PS: On a totally unrelated note, has GameDev moved to a SLOWER server? I''m having major speed issues with it here, and I''m on cable :/

##### Share on other sites
I quite like Jumpster''s break method. At least you feel like you''re cutting the loop short legitimately. I guess it''s just preference though.

I was worried something weird might happen like LordElectro said: ''memory cleaning up problems''.

Paulcoz.

##### Share on other sites
quote:
Original post by paulcoz
Just wondering, is it bad practice to "return" in the middle of a loop in a function like this (I''ve only coded it like I have to show you what I mean). You can see that the first ''return'' affects the code flow so that the function quits immediately upon obtaining an answer - is it o.k. to do that in the middle of the while loop (which has not finished)?

Either doing a return in the middle of the function (loop or no loop) or using either ''continue'' or ''break'' is exactly the same as using a ''goto''. Refer to one of the endless ''goto: good or bad'' flame wars for more details

imho, the best option is whatever''s going to make sense to you when you look at it again in 6 months. never using any break/goto/return in he middle of a loop will meet some people''s ideas of a good coding style, but can force horribly convoluted code that''s virtually impossible to understand. code length also matters - if the entire function fits on one screen, it''s easier to follow the code than if you have to constantly use page up/page down to see the whole function. (ie small and complex, or larger but with a simple linear flow.)

one way to check is to count how many paths through a function there are. the higher that number the more complicated it''s likely to be, but there''s no absolue limit - if you break up a function unnaturally then each function may be simple, but the system containing those functions will be complex, meaning the problem wasn''t actually solved.

if all else fails, you''re allowed to comment your code a quick comment can point out that you''re returning from the middle of the loop for a reason, then when you come back to the code, you''ll know what you were trying to do, rather than waste time trying to work it out again.

the short answer to your question is "it depends, but it''s perfectly valid at times."

(incidentally, colour coded code is a good thing, but not always available - printed code doesn''t usually have coloured text, colour blind people read code too - relying on nothing but colour isn''t usually a good plan.)

does that help?

##### Share on other sites
There is one more thing though. The asm code for a return is longer than the asm code for a break. So if you are optimizing often used inner loops it can make a difference (loops are faster if they fit into a single 16 byte cache line). But that''s just in extreme cases.

Oh, and I can''t agree with the "return sticking out" thing. All keywords are colored the same in my editor (msvc++). If you have a different editor, then that''s fine.

cu,
Prefect

##### Share on other sites
IMHO i would say yes especially if speed is
required however you should ensure that any
newed objects are deleted before returning ie

  TObject *p = new TObject();while(i < 10){ if(i == CheckInt){ delete p; return; }}delete p;

##### Share on other sites
IMHO i would say yes especially if speed is
required however you should ensure that any
newed objects are deleted before returning ie

  TObject *p = new TObject();while(i < 10){ if(i == CheckInt){ delete p; return; }}delete p;

##### Share on other sites
A lot of scientific proofs of algorithms have preconditions and postconditions, which by their nature requires that you start at the start and end at the end. This is why a lot of computer scientists might prefer that kind of approach. But for those people doing ''real-world'' applications, enforcing the 1-to-1 rule is just likely to make the code longer and slower.

##### Share on other sites
As an irrelevant sidenote, bool is actually never 0 or 1. It is either true or false. So you should return true instead of 1, even though C/C++ understands true as 1 and false as 0.

##### Share on other sites
I have not used GOTO in ages, with the exception of using it as a way to comment out large blocks of code in VB, which apparently doesnt have multiline comments, because MS failed to consider we might ever need them, just like they failed to consider we might ever use more than 640KB of memory. I stopped using them soon after i started programming. They are a lot different than mere breaking out of a loop, which still forces some structure on your code. Goto lets you run a muck all over the code, messing much stuff up. There is just no need for goto, the beauty of a high level language is that things can generally be done in a better and neater way using more sophisticated methods than the horrible goto. The moment you start using goto, you start losing control of your code.

##### Share on other sites
I have not used GOTO in ages, with the exception of using it as a way to comment out large blocks of code in VB, which apparently doesnt have multiline comments, because MS failed to consider we might ever need them, just like they failed to consider we might ever use more than 640KB of memory. I stopped using them soon after i started programming. They are a lot different than mere breaking out of a loop, which still forces some structure on your code. Goto lets you run a muck all over the code, messing much stuff up. There is just no need for goto, the beauty of a high level language is that things can generally be done in a better and neater way using more sophisticated methods than the horrible goto. The moment you start using goto, you start losing control of your code.

##### Share on other sites
Whether I use a return or a break or a boolean value in the while loop, I want the loop to stop once I have obtained an answer regardless of how many more entities there are to check for a certain criteria:

(1) check an unknown no. of entities (hence while or do)

(2) if any one of them meets the test conditions, I have the information I require, so do not bother testing the other entities.

I thought it would be pointless to do this:

bool lessthanten = FALSE;
while (count < 10 && !lessthanten)
(
if condition met (lessthanten = TRUE)
)

if (lessthanten)
return 1;
else
return 0;

That is almost like checking the same thing twice which would surely be a waste of time when you can use a return?

Paulcoz.

Edited by - paulcoz on January 11, 2001 5:57:24 PM

##### Share on other sites
quote:
Original post by LordElectro

I have not used GOTO in ages, with the exception of using it as a way to comment out large blocks of code in VB, which apparently doesnt have multiline comments, because MS failed to consider we might ever need them, just like they failed to consider we might ever use more than 640KB of memory.

Uh, hate to tell you but 640K was *not* MS''s fault (well, OK, it was, but only within the grand total of one meg). The multiline comments I''ll give you though ;-)

quote:
I stopped using them soon after i started programming. They are a lot different than mere breaking out of a loop, which still forces some structure on your code. Goto lets you run a muck all over the code, messing much stuff up.

Being able to code in the first place allows you to muck up your computer - so?

quote:
The moment you start using goto, you start losing control of your code.

Woah, thanks for the vote of confidence there... guess that throws away any chance I had of being able to write anything non-trivial in assembler, huh?

##### Share on other sites
  bool lessthanten = false;while (!lessthanten && count++ < 10){ lessthanten = (condition met);}return lessthanten;

With that example you just gave paul, I would write it as it is above.

This accomplishes:

1) as soon as lessthanten == (condition met), you exit.
2) If condition is never met, after 10 tries, you exit.

Again, it''s just a preference though. And I do agree that the double check would be a waste of time.

Regards,
Jumpster

##### Share on other sites
Yeah I guess the blue return would only help M\$ & borland compiler users that can see the color blue (incidently color blind people tend to confuse red&green but still notice the difference from black)
Don''t some linux & other unix compilers have color enhanced code?

...
I don''t think the goto''s that were use in the D3D example to handle the error condition on init were any worse than either example I gave.

There''s a new favor of asm now-a-days, and you could in theory make the program without using any explicit jmps by using them in controlled macros...

I think there''s no serious problem using gotos so long as you only jump elsewhere in the same function. I haven''t used one in a long time, and in fact feel that my FFT code is much easier to understand becuase it doesn''t use any (unlike nearly every other one on earth ). But in performance coding they''re something you just have to accept.

...
If Ii allocate memory, I tend to store it in a class property, so I relie on safe deletes to do my clean up. With rare exception do I allocate memory for a function and then deallocate it before returning (frag-men-ta-tion).

Magmai Kai Holmlor
- The disgruntled & disillusioned

##### Share on other sites
Would you prefer your compiler just tell you the first error and stop? If you can think of no reason now, and will not think of a reason later why you might want to continue on after encountering an error then it most likely doesn't matter. It might matter to someone else, or even you, later when it becomes obvious why you need to keep going, but hey, that's later and this is now. Why do today what we can put off until tomorrow?

One of the rules of structured programming is that a routine has exactly one entry and one exit point. Structured programming is a silly waste of time. After all it was replaced by modular programming which was in turn replaced by object oriented programming. Hum, or was it that modular programming built upon the foundation of structured programming and object oriented programming built upon the foundation of modular programming. Details, details, who can keep track of them.

Edited by - LilBudyWizer on January 11, 2001 11:33:50 PM

##### Share on other sites
If you are going to talk about goto usage (again...), I feel the need to boast. I don''t even KNOW HOW to do a goto! So you will never find them in my code There. I said it. Feel free to ignore this post (which I almost spelled poast ).

--------------------

You are not a real programmer until you end all your sentences with semicolons; (c) 2000 ROAD Programming

You are unique. Just like everybody else.

Visit the ROAD Programming Website for more programming help.

##### Share on other sites
quote:
Original post by Yanroy

If you are going to talk about goto usage (again...), I feel the need to boast. I don''t even KNOW HOW to do a goto! So you will never find them in my code

Well, beat this: Seeing as i''m a self taught programmer, and I started my learning in Borland C++ Builder 3.0 (cough ), I developed some strange habits in my code... I saw ''return'' in other people''s code (I think Carmack''s... not sure what it was I was trying to figure out though) so I thought they were for the l33t h4x0rz, or something. However, I became frustrated by not being able to get out of a function before it finished, so I stumbled across ''goto''. So, every time I wanted to bail out of a function, i''d have a lable defined right at the end of it (called ''End:'' usually ) and where i''d now put ''return'' I put ''goto End;''. Hah. I thought I was the bees-knees.
Those were the days...

Insomnia

##### Share on other sites
quote:

Woah, thanks for the vote of confidence there... guess that throws away any chance I had of being able to write anything non-trivial in assembler, huh?

Blah blah yea i know, but if u noticed, i was speaking of high level languages, not assembly.

##### Share on other sites
quote:
Original post by LordElectro

[quote]
Woah, thanks for the vote of confidence there... guess that throws away any chance I had of being able to write anything non-trivial in assembler, huh?

Blah blah yea i know, but if u noticed, i was speaking of high level languages, not assembly.

Either it works or it doesn''t, regardless of what level of language you''re using. It''s all a matter of whether or not you have the discipline not to screw it all up. In fairness, the higher level constructs are good at making the code more self-documenting (in much the same way as ret is a nice way of not having to pop registers and jump yourself).

##### Share on other sites
Assembly language does not preclude the use of structured programming and it is in fact of greater benefit within assembler. It isn''t whether you use gotos or their equivilants, but rather the manner in which control flows through the program. C/C++ programs in all likelyhood will be structured whether the programmer is aware of the rules of structured programming or not. Within assembler it is unlikely to be structured unless the programmer is aware of structured programming and makes a specific effort to write a structured program. It is effectively far more important to use structured programming within assembler than in any other language because if you don''t make the effort it will be far less structured than any other language excluding machine code which is effectively the same thing.