C Style

Frank Adams franka at mmintl.UUCP
Tue Sep 17 10:08:22 AEST 1985


In article <180 at chinet.UUCP> rlk at chinet.UUCP (Richard L. Klappal) writes:
>The question:
>	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();

Leaving aside the fact that you left out some statements in the second
version, I would not use either of these styles.  I don't like either gotos
or side effects in conditionals.  I would use something like one of the
following:

	noecho();		/* turn off echo */
	for (;;) {
	   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 */
	   }
	   else {
	      break;
	   }
	}
	addch(ch);		/* echo the valid character */
	refresh();		/* update screen */
	. . .

or

	noecho();		/* turn off echo */
	havech = FALSE;
	while (! havech) {
	   move(4,10);		/* set cursor position */
	   refresh();		/* update screen */
	   ch = getch();	/* get input character (without echo) */
	   havech = (ch >= '1' && ch <= '5') || ch == 'E';
	 			/* valid input is 1 thru 5 or 'E' */
	   if (! havech) {
	      putchar(BELL);	/* sound bell on invalid input */
	   }
	}
	addch(ch);		/* echo the valid character */
	refresh();		/* update screen */
	. . .


Frank Adams                           ihpn4!philabs!pwa-b!mmintl!franka
Multimate International    52 Oakland Ave North    E. Hartford, CT 06108



More information about the Comp.lang.c mailing list