break, continue, return, goto

Mike Shannon mikes at 3comvax.UUCP
Tue Nov 19 06:10:54 AEST 1985


Michael Baldwin:
> Can anyone suggest a recoding of the following example without using
> multiple returns?  Of course it can be done, but in a clearer, simpler
> way?  Remember, this is exactly the same as using loops with continue.
> 
> core(file)
> char	*file;
> {
> 	if ((fd = open(file, O_RDONLY)) < 0) {
> 		perror(file);
> 		return;
> 	}
> 	if ((n = read(fd, &u, sizeof u)) == 0) {
> 		puts("zero length");
> 		return;
> 	}
> 	if (n < sizeof u) {
> 		puts("too small");
> 		return;
> 	}
> 	if (BADMAG(u.u_exdata.ux_magic)) {
> 		puts("not a core dump");
> 		return;
> 	}
> 
> 	/* process core dump */
> 	printf("%d/%d %s", u.u_uid, u.u_gid, ctime(&u.u_start));
> 	printf("$ %s\n", u.u_comm);
> 	/* ... etcetera */
> }
--------
OK, here goes:
--------
core(file)
char	*file;
{
	if ((fd = open(file, O_RDONLY)) < 0) {
		perror(file);
	}
	else if ((n = read(fd, &u, sizeof u)) == 0) {
		puts("zero length");
	}
	else if (n < sizeof u) {
		puts("too small");
	}
	else if (BADMAG(u.u_exdata.ux_magic)) {
		puts("not a core dump");
	}
	else { /* all is OK */
		/* process core dump */
		printf("%d/%d %s", u.u_uid, u.u_gid, ctime(&u.u_start));
		printf("$ %s\n", u.u_comm);
		/* ... etcetera */
	}
}
-----
	This case is *exactly* the situation where I don't like to see
multiple returns.  If there's one thing I hate, it's seeing a bunch of
branch statements.  Then I have to scratch my head and think "Ok, where
can I get to as I scan down this code?". Really.  When I see goto's,
multiple return's, continue's, etc, immediately, in my head, I think,
"Oh Crap! Now I really have to pay attention!".
	I really think my second way is better.  If I had to debug this
code, I would read it and it's immediately obvious what's going on.  This
'multiple error filter' use of the if.... else if..... else  seems
so intiutive to me that I can trivially scan it and instantly know
what's going on.  Of course, it's *always* important to pay attention
when reading/debugging someone else's code. (or even your own! :-)
	But why make me expend any more mental calories than I need to?
	Along the same line, if you have a situation like this:
	if(a) {
		something
	}
	if(b) {
		something else
	}
and (a) and (b) are mutally exclusive conditions, then please do everyone a
favor, and do it this way:
	if(a) {
		something
	}
	else if (b) { /* notice the ELSE */
		something else
	}

that way, when someone comes along later to read your programs, they
won't have to worry about "what if both are supposed to happen?"
-- 
			Michael Shannon {ihnp4,hplabs}!oliveb!3comvax!mikes



More information about the Comp.lang.c mailing list