4. Lex program that distinguishes keywords, integers, floats, identifiers, operators, and comments

 

Lex program that distinguishes keywords, integers, floats, identifiers, operators, and comments

/*Lex program that distinguishes keywords, integers, floats, identifiers, operators, and
comments in any simple programming language.*/ 
 
%{
enum{INTEGER,FLOAT,IDENTIFIER,OPERATOR,COMMENT};
%}
digit [0-9]
letter[A-Za-z_]

%%
" "|"\t" ;
{digit}+   { return INTEGER; }
{digit}+\.{digit}+ { return FLOAT; }
'+' |
'-' |
'*' |
'/' { return OPERATOR; }

{letter}({letter}|{digit})* { return IDENTIFIER; }
"/*" { return COMMENT;}
%%
int main(void)
{
  int result;
  int running = 1;
 while(running)
 {
  result = yylex();
  switch(result)
                {
  case INTEGER: printf("integer"); break;
  case FLOAT: printf("float"); break;
  case OPERATOR: printf("operator"); break;
  case IDENTIFIER:printf("identifier"); break;
  case COMMENT: printf("comment"); break;
  }
 }
return 0;
}
 
// Output of the above Program
Lex program that distinguishes keywords, integers, floats, identifiers, operators, and comments
Lex program that distinguishes keywords, integers, floats, identifiers, operators, and comments

Comments

Popular posts from this blog

Compiler Design

3. Lex program to find the length of the longest word

6. Lex program to count the number of words,small and capital letters, digits and special characters in a C file