comments in lex

Glen Dudek dudek at harvard.ARPA
Thu Jul 4 08:42:39 AEST 1985


What I consider the "best" (read "most efficient") way to eat C or
PL-1 style comments in lex is as in the ANSI-C standard yacc/lex
grammar recently posted to the net:

%%
"/*"			{ comment(); printf("comment"); }
%%
comment()
{
	char c, c1;
loop:
	while ((c = input()) != '*' && c != 0)
		putchar(c);
	if ((c1 = input()) != '/' && c != 0) {
		unput(c1);
		goto loop;
	}
	if (c != 0)
		putchar(c1);
}

My favorite way is to use the following lex expression:

%%
"/*"("/"|("*"*[^*/]))*"*"+"/"	{ printf("comment"); }
%%

Although it may make your head hurt, it's interesting to figure out.

	Glen Dudek



More information about the Comp.unix mailing list