I am coding a simple calculator parser program using flex and bison. flex code is given as:
calc.l
%{
#include "fb1-5.tab.h"
%}
%%
"+" { return ADD; }
"-" { return SUB; }
"*" { return MUL; }
"/" { return DIV; }
"|" { return ABS; }
[0-9]+ { yylval = atoi(yytext); return NUMBER; }
\n { return EOL; }
[ \t] { /* do nothing */ }
. { return *yytext; }
%%
and the bison code is given as:
calc.y
%{
#include <stdio.h>
#include <stdlib.h>
%}
%token NUMBER
%token ADD SUB MUL DIV ABS
%token EOL
%%
calclist:
| calclist exp EOL { printf("= %d\n", $1); }
;
exp: factor
| exp ADD factor { $$ = $1 + $3; }
| exp SUB factor { $$ = $1 - $3; }
;
factor: term
| factor MUL term { $$ = $1 * $3; }
| factor DIV term { $$ = $1 / $3; }
;
term: NUMBER
| ABS term { $$ = $2 >= 0 ? $2 : -$2; }
;
%%
main(int argc, char **argv)
{
yyparse();
}
yyerror(char* s)
{
fprintf(stderr, "Error: %s\n", s);
}
For every input the answer is always 62.Even if I am giving spaces between the numbers or not the answer is always same. Even if the answer should be completely different. Like for 1+2+3 and also for 100+200+300 the answer given is always 62.