Tuesday, 4 February 2014

Program Structure in Lex Analyzer

Program Structure in Lex Analyzer:

To write a program in lexical analyzer we need to aware of program structure:

%{
/* definition Section */
%}
%%
/*Rules section : Pattern and Action
%%
main( )
{
/* your program*/
}

Let's go into Detail :

Definition Section: This is especially important when we  have header files that must be included for code later in the file to work.You can include the header files and can initialize the variables that can use in any section of the entire program.

e.g.   #include<stdio.h>  /*you can include stdio.h header file for the further use.*/

Rules section : Each rule is made up of two parts: a pattern and an action, separated by whitespace. The lexer that lex generates will execute the action when it recognizes the pattern which are made up regular expressions.

e.g.  @|#|$|%   printf("Special character occured %s",yytext);

 If any special character you write at the time of execution then it will print the statement written into the printf statement and value or that character will be store in the predefined yytext variable via yylex.

User Subroutine Section: It can consist of any Legal C code. Lex copies it to the C file after the end of the lex generated code.
%%
main ( )
{
yylex();
}
The lexer produced by lex is a C routine called yylex(). Unless the actions contain explicit return statements, yylex() won't return until it has processed the entire input.


No comments:

Post a Comment