DOC HOME SITE MAP MAN PAGES GNU INFO SEARCH PRINT BOOK
 
lex

The subroutines section

Subroutines can be used in a lex specification for the same purposes as in other C programs. Code used in actions for several rules can be written once and called when needed. Other reasons to use a subroutine are to highlight some code of interest and to simplify the rules section, even if the code is used in one rule only. As an example, consider the following routine, which is used to compile statistics on an input text:

   %{
   int the_count = 0;
   int a_count = 0;
   int an_count = 0;
   %}
   article         a|an|the
   %%
   {article}       do_article(yytext);
   .
   .
   .
   %%
   do_article(s)
   char *s;
   {
           if (!strcmp(s,"a")) {
                   a_count++;
                   return 0;
           } else if (!strcmp(s,"an")) {
                           an_count++;
                           return 0;
                   } else if (!strcmp(s,"the")) {
                                   the_count++;
                                   return 0;
                           }
           printf("text not an article: %s\n",s);
           return 1;
   }
Other examples of subroutines are programmer-defined versions of the I/O routines input(), unput(), and output(), which will be discussed later. Subroutines that may be exploited by many different programs should probably be stored in their own individual file or library to be called as needed.
Next topic: Advanced lex usage
Previous topic: Abbreviations

© 2003 Caldera International, Inc. All rights reserved.
SCO OpenServer Release 5.0.7 -- 11 February 2003