Sign in to follow this  

Breaking out of loops, in C?

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

If you intended to correct an error in the post then please contact us.

Recommended Posts

Ive been told by a lecturer at univeristy that you shouldn't use break statements in 'For' loops to exit them. he says this is "dangerous" ................................. why is it? I havent been able to get hold of him to ask so I thought this would be just as good to post it here. [Edited by - Arclight on December 15, 2004 9:27:01 AM]

Share this post


Link to post
Share on other sites
No it was 'Break' exact comment he wrote on my coursework is -

<Quote>Break - Not used in For dangerous! Only used in Switch.</Quote>

And he penialised me down to a high C grade :(

Share this post


Link to post
Share on other sites
It is debatable, so take it with a grain of salt. The loop control keywords are not universally loved because it is yet another way for the flow of execution to leave that loop. Without them, only the loop condition keyword controls the loop. When you use things like break, you have multiple ways out. So in this sense it isn't something you should use regularly. Ditto with continue. Everything has its place, including goto. Your teacher may overexaggerate (whether intentionally or unintentionally) some things right now in order to prevent you from relying on these constructs in every loop.

However, if he is grading your work, then play by his rules. Ask him about it in private and explain that you think dropping your grade that much is unfair. It is a bit harsh, if I were a teacher I would have deducted 5 points or so.

Share this post


Link to post
Share on other sites
So its possible he is just making a point that I shouldnt exit the loop through anything other than the condition, just to teach me a resonable programming sytle?




Git......... well he didnt have to cut my grade in half to show it. A simple postit would have been enough.

Share this post


Link to post
Share on other sites
Sounds a bit harsh to me, for something that's valid working code and mainly his opinion that it's dangerous.

FWIW, I use break in a for loop when I'm doing something like looking for the first item that meets some condition. The for loop is set up to search through the entire array, the break is for when I found what I'm looking for. An accompanying comment is enough so that anyone else realizes there's two ways out.

I find it much cleaner than having a bunch of && statements in the loop condition.

Share this post


Link to post
Share on other sites
The way I remember it (from the Code Complete book):

When using the for loop the initialization, condition checking and incrementing are all done in the head of the loop. Since all this information is in one place, the assumption should be that this controls the entire loop.

A while loop on the other hand only does condition checking, so the fact that the initialization and incrementing is independent of the loop makes it more acceptably to break out of the loop.

Share this post


Link to post
Share on other sites
If he penalizes you for using break, then you could gig it to him by forcing your test condition to be true (changing a variable to force equality or whatever) and then using continue to jump to the next iteration of the loop, at which point the actual condition of the loop will break execution, not the break.

'Swhat I'd do if he didn't let me use break.

Share this post


Link to post
Share on other sites
Ask him how he would do a search then? You need a loop for sure, unless you plan on hardcoding 10millions lines. So what, I should waste time iterating through the whole list or array (whatever you are searching through) after I have found what I am looking for, just becasue I should use a break? That sounds like sloppy coding and waste of cycles.

Share this post


Link to post
Share on other sites
breaking at an arbitrary point in a for loop can be done thusly:


srand(time(NULL));

bool keep_looping = true;

for(int count=0; count<100 && keep_looping == true; ++count) {
if(rand()%100 == 1) // Say you needed to break here
keep_looping=false;
else { /* Keep doing stuff. This needs to be here to stop the following code executing after your "break" */
cout << count << endl;
}
}


edit: Damn, beaten.
Edit again: Added comments.

[Edited by - The Rug on December 15, 2004 12:55:24 PM]

Share this post


Link to post
Share on other sites
Quote:
Original post by Kars
The way I remember it (from the Code Complete book):

When using the for loop the initialization, condition checking and incrementing are all done in the head of the loop. Since all this information is in one place, the assumption should be that this controls the entire loop.

A while loop on the other hand only does condition checking, so the fact that the initialization and incrementing is independent of the loop makes it more acceptably to break out of the loop.


Minor point, but the for loop's initialization is done before the head (what I think of as the head anyway) so that's no different from the while loop. More importantly, simply saying "x is done independent of the loop" doesn't explain in any way how it's more acceptable. I suspect you're either misquoting or leaving out something important.

OP, ask yourself this: If the ability use a break in a for loop were dangerous (whatever the hell that even means in a programming context), why would it be part of the language?

A friend of mine was given a similar for-break warning by a professor recently and I suspect it's just a bunch of high falutin purist comp sci phds trying to make life difficult for freshmen.

Share this post


Link to post
Share on other sites
Break and continue are little more than syntactic sugar. I'm not sure I'd say I use them, "all the time," however -- and maybe thats what this teacher is trying to impress upon you.

As for appeasing people with whom you don't agree with, that is part of life. Just ask your teacher after class about it. You'd be amazed how reasonable teachers are if you actually talk with them.

Share this post


Link to post
Share on other sites
Unconditionally forbidding keywords is nothing but stupid, everything in C has it's place. Fight your teacher's decision or at the least give him a link to this thread. Letting "The Methodology" blindly dictate what you can and can not do leads to mediocre programmering, at best.
Note that disallowing multiple return points would also prevent the use of exceptions.

Share this post


Link to post
Share on other sites
Do something like this and ask your prof if he prefers it:

for(int count=0; count<100 && rand()%100 != 1; cout << count << endl, ++count)
;


[grin]

(does the same as my previous code)

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
The professor's constraint may have a broader message than you realize. In programming, there are often times numerous ways to solve a problem. Your professor may be trying to illustrate this by setting up these types of restrictions. A couple different solutions have been presented here, and there undoubtedly dozens more.

I'm not sure about your school's computer science program, but the program I went through taught more about the methodology of programming, rather than the nuts and bolts of a single language. Just because C/C++ has a break statement, can you guarantee that every programming language you will work with will have similar functionality? Most do, but I cannot say with absolute certainty than all do. At some point, you may need to work with a language that doesn't have a specific functionality you are used to using.

Also, there will be times (in both professional and personal situations) when you will be required to work within arbitrary constraints. This is one of them.

Share this post


Link to post
Share on other sites
It doesn't seem that the OP was told "don't use break", so taking off so many points for something he didn't know about that isn't even wrong doesn't seem fair.

Share this post


Link to post
Share on other sites
AP - plenty of pure and semi-pure functional languages don't have or need break statements. Recursion is the proper way of implementing 'loops' that require break in C.

However, since to be efficient you need a compiler capable of generating proper tail call optimized code, using break in C/C++ like languages is still necessary. I think it's a bit stupid to ban usage of something that is required to make code efficient and readable in C/C++/Java/C#.

Share this post


Link to post
Share on other sites
It is considered proper practice (by somebody) to include all conditionals in the loop's condition and use if around blocks that should not be executed in the loop, like
while(more lines to proccess && (result == 0))
{
result = do_op_1();
if(result == 0)
{
result = do_op_2();
}
if(result == 0)
{
result = do_op_3();
}
if(result == 0)
{
result = do_op_4();
}
}

Share this post


Link to post
Share on other sites

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

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this