Jumping into blocks

KW Heuer kwh at bentley.UUCP
Thu Apr 24 02:34:14 AEST 1986


In article <275 at copper.UUCP> copper!stevesu (Steve Summit) writes:
>Most people agree that goto's are pretty acceptable for handling
>error conditions.  For instance:
>
>	if(stbuf.st_uid != getuid()) {
>nope:		printf("I don't think you want to delete this file.\n");
>		return;
>	}
>	if(strcmp(name, "vmunix") == 0) goto nope;
>	unlink(name);
>	return;

As has been pointed out, this particular example can be handled easily with
the || operator.  But here's a real example I keep running into:

	while (argc > 1 && argv[1][0] == '-') {
	    switch (argv[1][1]) {
	    ...
	    default:
usage:		fputs("usage: a.out [flags] args\n", stderr);
		exit(1);
	    }
	    --argc;  ++argv;
	}
	if (!aflag && !bflag && !cflag) goto usage;

A trivial variation is to have "goto usage" after "default:" and put the
actual usage message inside the "if" -- this makes it a forward goto, but
still into a block.

So, assuming that goatooze are acceptable for error handling, but jumping
into a block is forbidden, what's the best way to write this?  Use two
braches, and hide the common code at the bottom of main()?  Set an error
flag and test it outside the while?  (Ugh, that requires an artificial
boolean *and* a break statement.)  Make usage() a non-returning function
instead of a label?  (My usual preference.)  Duplicate the code?

Karl W. Z. Heuer (ihnp4!bentley!kwh), The Walking Lint



More information about the Comp.lang.c mailing list