Put your code... (was Re: gotos

kenny at uiucdcsb.cs.uiuc.edu kenny at uiucdcsb.cs.uiuc.edu
Tue Apr 26 09:56:00 AEST 1988


[Part 2: Finite-state recognizers and pushback]

EXAMPLE 4 shows how _goto_s may be used to good effect in finite-state
recognizers for processing text.  Here we see, however, how
programming tools have improved since Knuth's day.

Most experienced C programmers, at least from among those workig on
UN*X, would code EXAMPLE 4 with Lex [Lesk75]:

%{
int column = 0;			/* Column in the output */
%}
%%
'//'	{ putchar ('\n'); column = 0; }
'/'	{ column = tabulate (column); }
'.'	{ ECHO; putchar (' '); column += 2; }
\n	{ ; }
.	{ ECHO; ++column; }
%%
int tabulate (column)
    int column;
{
  ....
}

Without Lex, there is another possibility, which is to use the
`ungetc' feature of the standard I/O library.  In this case, the
procedure winds up being:

	c = getchar ();
	switch (c) {
		case EOF:
			return;
		case '\n':
			break;
		case '/':
			if ((c = getchar ()) == '/') {
				putchar ('\n');
				column = 0;
				}
			else
				column = tabulate (column);
			break;
		case '.':
			putchar (c);
			putchar (' ');
			column += 2;
			break;
		default:
			putchar (c);
			column += 1;
			break;
	}

Only if ungetc is unavailable do we need to resort to Knuth's
examples.  In this case, I actually prefer the use of the temporary
Boolean; it may be interpreted as `there is a character in the ungetc
buffer.'



More information about the Comp.lang.c mailing list