LEX rule, anyone???

Esmond Pitt ejp at bohra.cpg.oz
Wed Dec 6 12:49:18 AEST 1989


In article <601 at vice2utc.chalmers.se> d5kwedb at dtek.chalmers.se (Kristian Wedberg) writes:
>A question from a friend of mine, P{r Eriksson:
>
>	Does anyone know how to write a LEX rule for C comments,
>	ie for everything between /* and */, nesting not allowed?

You don't want to do this in one rule, because a sufficently long C
comment will overflow lex's token buffer, with dire results. Three
rules do it; the order is important.

%start COMMENT
%%
<COMMENT>"*/"	BEGIN(INITIAL);
<COMMENT>.|\n	;
<INITIAL>"/*"			BEGIN(COMMENT);

If you are using lex you will find this slow, so you will probably replace
the above with something like this:

%%
"/*"	{
	int c;

	for(;;)
	{
		c = input();
		if (c == '*')
		{
			c = input();
			if (c == '/')
				break;
			unput(c);
		}
	}
}

(E&OE)

-- 
Esmond Pitt, Computer Power Group
ejp at bohra.cpg.oz



More information about the Comp.lang.c mailing list