break, continue, return, goto

Jeff Kresch jak at adelie.UUCP
Sat Nov 16 04:49:36 AEST 1985


> 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 */
> }

How about:

 core(file)
 char	*file;
 {
        bool error = TRUE;

 	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
                error = FALSE;
        if (error)
                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 */

This version is a good deal smaller, which, in this case, makes the
program easier to read.

But I agree with the basic premise that multiple breaks, continues, and
returns are not the same as, and as bad as, gotos.  The difference is
that the former work within the context of a structure.  A return always
returns to the same place.  Breaks and continues function the same way
within loops.  Gotos can be used arbitrarily, and that is the danger.

                                                They call me
                                                JAK

"I just like to see may name in print."



More information about the Comp.lang.c mailing list