Article View: comp.lang.c.moderated
Article #2135Re: use of the break statement
From: Ken Goldman
Date: Fri, 01 Mar 1996 15:35
Date: Fri, 01 Mar 1996 15:35
42 lines
2136 bytes
2136 bytes
bill_winn@acm.org (Bill Winn) writes:
> In article <4gnbcp$biq@solutions.solon.com>, news@dcs.warwick.ac.uk
> composed...
> >In code that I write, and see, every day, break is very commonly used
> >to exit a loop. In fact, I sometimes have a break being the /only/ way
> >to exit a loop. (Something like perl's split loop body would be a nice
> >addition to the language.) I don't consider it to be in any way bad
> >style.
> >
>
> I beg to differ. break, used in the context of loops, is nothing more than
> a glorified goto statement. If you have conditions that force a loop to
> stop executing why not just have a flag that is set when the loop is to
> terminate? Sure, you have to go to the top of the loop (in the case of for
> and while) to test for the condition, but I would venture a guess that doing
> such will not cause your system to fail.
>
Here's when I use "break" to get out of the for loop. Polite
criticism is welcome.
The problem with going back to the top of the loop to check a flag
is that the loop counter is processed before the test. For example:
/* returns the number that suceeded, returns MAX if failed */
for (i = 0 ; i < MAX ; i++) {
if (try_something(i) == SUCCESS) {
break;
}
}
return(i);
Yes, I suppose that I could set a success flag, test for it in the loop,
and then conditionally decrement i before the return. Would that really
be more clear than the break?
(I'm not arguing performance. I agree that generally, clarity of
code is more important.)
--
Ken Goldman kgold@watson.ibm.com
Technical Details
Message-ID:
<4h75gn$4rq@solutions.solon.com>Path:
arc1-ca.pugleaf.net!solon.com!not-for-mailReferences:
<4gfcl7$2ls@solutions.solon.com> <4gnbcp$biq@solutions.solon.com> <4h2s54$o3@solutions.solon.com>Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!solon.com!not-for-mail From: kgold@watson.ibm.com (Ken Goldman) Newsgroups: comp.lang.c.moderated Subject: Re: use of the break statement Date: 1 Mar 1996 09:35:51 -0600 Organization: IBM T.J. Watson Research Center Sender: clc@solutions.solon.com Approved: clc@solutions.solon.com Message-ID: <4h75gn$4rq@solutions.solon.com> References: <4gfcl7$2ls@solutions.solon.com> <4gnbcp$biq@solutions.solon.com> <4h2s54$o3@solutions.solon.com> NNTP-Posting-Host: solutions.solon.com