C Style

Doug Gwyn <gwyn> gwyn at brl-tgr.ARPA
Sat Sep 14 04:39:23 AEST 1985


> 	Which of the following code segments is more understandable,
> 	(readable, structured, etc) given the current attitudes
> 	about the presence of goto's in programming?
> 
> GOTO VERSION:
> 	. . .
> 	noecho();		/* turn off echo */
> retry:
> 	move(4,10);		/* set cursor position */
> 	refresh();		/* update screen */
> 	ch = getch();		/* get input character (without echo) */
> 	if ((ch < '1' || ch > '5') && ch != 'E')
> 	{			/* valid input is 1 thru 5 or 'E' */
> 		putchar(BELL);	/* sound bell on invalid input */
> 		goto retry;
> 	}
> 	addch(ch);		/* echo the valid character */
> 	refresh();		/* update screen */
> 	. . .
> 
> versus NO GOTO VERSION
> 
> 	for ( ; (((ch=getch()) < '1' || ch > '5') && ch != 'E') ; )
> 		putchar(BELL);
> 	addch(ch);
> 	refresh();

There are several other non-GOTO ways to rewrite the first example:

	move( 4, 10 );			/* position cursor */
	refresh();

	valid = false;
	while ( !valid )
		switch ( ch = getch() )	/* validate input char */
			{
		case 'E':
		case '1':
		case '2':
		case '3':
		case '4':
		case '5':
			valid = true;
			break;

		default:		/* not valid */
			putchar( BELL );
			}

	addch( ch );			/* echo valid input char */
	refresh();

Although this introduces an additional (Boolean) variable, which is
one of the problems with goto-less programming, the variable has
very clear meaning and may actually help in understanding the code.

> I guess what I'm really asking is:
> 	If you had to modify this program, written by someone else who
> 	commented it sparsely, which style would you prefer to work on?

Mine, of course.

Actually, I would suggest packaging similar code into some more general
module, perhaps

char getvalid( Point where, const char *prompt, const char *valids );

The value of doing this should be clear, but if not we can get into
the reasons for it.



More information about the Comp.lang.c mailing list