Search code examples
ccompiler-constructionflex-lexer

Why the below flex code doesn't show output?


digit  [0-9]
letter [A-Za-z]
%{
int count;
%}
%%
     /* match identifier */
{letter}({letter}|{digit})*  count++;
%%
int main(void) {
yylex();
printf("number of identifiers = %d\n", count);
return 0;
}

Doesn't work printf statement. can you explain what should i include in this code.


Solution

  • If you have an error with yywrap -- just add %option noyywrap:

    digit  [0-9]
    letter [A-Za-z]
    %{
        int count;
    %}
    
    %option noyywrap
    
    %%
         /* match identifier */
    {letter}({letter}|{digit})*  count++;
    %%
    
    int main(void) {
        yylex();
        printf("number of identifiers = %d\n", count);
        return 0;
    }
    

    Then compile:

    flex f.l
    gcc lex.yy.c
    

    Run and don't forget to send EOF at the end (with Ctrl-D):

    ./a.out
    a a a
    
    number of identifiers = 3