Sunday, 16 November 2014

YACC PROGRAM to evaluate an arithmetic expression involving operators + - * /



program to evaluate an arithmetic expression involving operators + - * /




5a.l
%{
#include"y.tab.h"
extern int yylval;
%}
%%
[0-9]+ {yylval=atoi(yytext);
            return number;}
[\t] {;}
[\n] {return 0;}
. {return yytext[0];}
%%

5a.y file
%{
#include<stdio.h>
int res=0;
%}
%token number
%left '+' '-'
%left '*' '/'
%%
stmt:expr {res=$$;}
;
expr:expr '+' expr {$$=$1+$3;}
    |expr '-' expr {$$=$1-$3;}
    |expr '*' expr {$$=$1*$3;}
    |expr '/' expr {if($3==0)
             exit(0);
             else $$=$1/$3;}
    |number
    ;
%%
void main()
{
printf(" enter expr\n");
yyparse();
printf("valid=%d",res);
exit(0);
}

void yyerror()
{
printf("invalid\n");
exit(0);
}

 

10 comments:

Total Pageviews