I'm working on multi function calculator from bison. I have found that if the following expression is passed into program, a wrong answer will be produced.
(1+2) * (2+1)
The above expression should produce 9. However it produces 6 in the following setup.
this is the bison code:
%token NUMBER
%%
statement_list: statement '\n'
| statement_list statement '\n'
;
statement: expression { printf("= %d\n", $1); };
expression: expression '+' term { $$ = $1 + $3; }
| expression '-' term { $$ = $1 - $3; }
| term { $$ = $1; }
;
term: term '*' factor { $$ = $1 * $3; }
| term '/' factor
{ if ($3 == 0)
yyerror("Division by zero");
else $$ = $1 / $3; }
| factor { $$ = $1; }
;
factor: '(' expression ')' { $$ = $2; }
| '-' factor { $$ = -$2; }
| NUMBER { $$ = $1; }
;
%%
This is flex code
D [0-9]
WS [ \t\v\f]
%%
{D}+ { yylval = atof(yytext); return NUMBER; }
"+" { return yytext[0]; }
"-" { return yytext[0]; }
"*" { return yytext[0]; }
"/" { return yytext[0]; }
"(" { return yytext[0]; }
")" { return yytext[0]; }
"\n" { return yytext[0]; }
{WS} {}
. {}
%%
Thanks, Ali