Lex and Yacc Calculator code
Implementation of Calculator using LEX and YACC Calculator code.
Lex and Yacc Calculator code-Lex
%{ # include # include "y.tab.h" # include %} %% [0-9]+(\.[0-9]+)? { yylval.dval=atof(yytext);return NUMBER;} [\t] ; /* ignore whitespace */ \n {return 0;} . return yytext[0]; %% int yywrap(void) { return 1; }
Lex and Yacc Calculator code-Yacc
%{ # include # include %} %union { double dval; } %token NUMBER ; %left '-''+' %left '*''/' %right '^' %type expr %% result: '='expr |expr {printf("%f",$1);} ; expr: expr'+'expr {$$=$1+$3;} | expr'-'expr {$$=$1-$3;} | expr'*'expr {$$=$1*$3;} | expr'^'expr { $$=pow($1,$3);} | expr'/'expr { if($3==0) yyerror("devide by zero"); else $$=$1/$3;} | '-'expr {$$=-$2;} | '('expr')' { $$=$2;} | NUMBER {$$=$1;} ; %% void yyerror(char *s) { fprintf(stdout,"%s\n",s); } int main() { yyparse(); return 0; }
Leave a Reply