Little
Little

Reputation: 3477

what is the error in the following flex and bison program?

I have been following a calculator example from the book Flex and Bison from O'Reilly and so far I have done the following.

I am using Flex and Bison for Windows, and for compiling it with Flex I have made it with the following command:

flex f4.l

and for getting the needed .exe file I have put:

gcc lex.yy.c -L "C:\Program\GnuWin32\lib" -lfl

Until this point the generated .exe file works just fine.

Now the book says that I should make the .y file to be compiled by bison, my code is:

File: f5.y

    /* simplest version of calculator */
%{
#include <stdio.h>
%}
/* declare tokens */
%token NUMBER
%token ADD SUB MUL DIV ABS
%token EOL
%%
calclist: /* nothing */ 
 | 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);
}

Two files are generated by Bison: f5.tab.c and f5.tab.h

My f4.l file is the following:

%{
# include "f5.tab.h"
int yylval;
%}
/* recognize tokens for the calculator and print them out */
%{
 int yylval;
%}

%%
"+" { return ADD; }
"-" { return SUB; }
"*" { return MUL; }
"/" { return DIV; }
"|" { return ABS; }
[0-9]+ { yylval = atoi(yytext); return NUMBER; }
\n { return EOL; }
[ \t] { /* ignore whitespace */ }
. { printf("Mystery character %c\n", *yytext); }
%%
/*main(int argc, char **argv)
{
 int tok;
 while(tok = yylex()) {
 printf("%d", tok);
 if(tok == NUMBER) printf(" = %d\n", yylval);
 else printf("\n");
 }
}*/

I compile my program with:

gcc f5.tab.c lex.yy.c -L "C:\Program\GnuWin32\lib" -lfl

The problem is when I run the compiled program, for example if I put:

2 + 3 * 4
= 1968511970
20/2
= 1968511970

why have I those answers? It seems that is displaying memory positions, I guess, any help?

Upvotes: 0

Views: 299

Answers (1)

user207421
user207421

Reputation: 310957

| calclist exp EOL { printf("= %d\n", $1); } 

You're printing the wrong thing. It should be:

| calclist exp EOL { printf("= %d\n", $2); } 

Upvotes: 2

Related Questions