break, continue, return, goto
Lowell Savage
savage at ssc-vax.UUCP
Wed Nov 6 05:13:48 AEST 1985
> This is in response to those who think that break, continue, and
> multiple returns are bad things. As with anything, they can be
> abused, but I find continue and multiple returns extremely useful
> for dealing with errors, and break for ending complicated search loops.
> In fact, that covers 99% of the ways I use them. Here are some typical
> examples:
>
> /* using continue for error handling in loops */
> for (i = 1; i < argc; i++) {
> if ((fp = fopen(argv[i], "r")) == NULL) {
> perror(argv[i]);
> continue;
> }
> if (some other reason this arg is bad) {
> process(error);
> continue;
> }
> /* code to deal with a good arg */
> while ((c = getc(fp)) != EOF)
> munch(c);
> }
Another possibility: use an "else if" type of construct.
for (i = 1; i < argc; i++) {
if ((fp = fopen(argv[i], "r")) == NULL)
perror(argv[i]);
else if (some other reason this arg is bad)
process(error);
else
while ((c = getc(fp)) != EOF)
munch(c);
}
It could be argued that this is clearer than the "for" loop using the
continues since the inner "while" loop is explicitly under conditional
control of the else statement. (But that's MY opinion.) This can also
be used for multiple returns (SOMETIMES!) or exits.
>
> /* using break for ending a complicated search loop */
> for (m = meeble; m < meeble + NMEEBLE; m++)
> if (m->glop == forp && m->zip == fweep) {
> printf("zeegle %2s", m->yorg);
> m->blazzo += IGUAP;
> break;
> }
>
And another possibility is changing the interation variable inside the
loop (GASP!) by changing the "break;" statement to "m = meeble + NMEEBLE;".
However, this will not help you any it you want to save the "m" that you
were looking for. In that case you can "find" your "m" with a "do-nothing"
for loop, and then check to see if you found it later and print out your
message. Like so:
for (m = meeble; m < meeble + NMEEBLE && m->glop == forp &&
m->zip == fweep; m++) ; /* find the right "m" */
if (m < meeble + NMEEBLE) { /* found one. */
printf("zeegle %2s", m->yorg);
m->blazzo += IGUAP;
}
These are my personal biases. Anyone that wants to share them will have
to fill out a 100-page non-disclosure agreement in octuplicate (without
carbons), send all copies with 2 dollars for processing to outer Tanzania,
wait two years, and chant "Mousy Dung was a bad guy." five hundred times.
All questions on this matter will be refered to the Bureau of non-violent
violence.
There's more than one way to be savage
Lowell Savage
More information about the Comp.lang.c
mailing list