Abhilash
Abhilash

Reputation: 2256

lex/bison program to evaluate an expression

The following is yacc code:

%{
#include<stdio.h>
#include<math.h>
%}
%token NUMBER
%left '-' '+'
%left '*' '/'
%nonassoc UMINUS
%%
statement:expression {printf("Answer=%g\n",$1);}
;
expression:expression'+'expression {$$=$1+$3;}
|expression'-'expression {$$=$1-$3;}
|expression'*'expression {$$=$1*$3;}
|expression'/'expression {if($3==0)
yyerror("Divide by Zero");
else
$$=$1/$3;
}
|'-'expression %prec UMINUS {$$= -$2;}
|'('expression')' {$$=$2;}
|NUMBER {$$=$1;}
;
%% 
int main(void)
{
printf("Enter the Expression");
yyparse();
printf("\n\n");
return 0;
}
int yyerror(char *error)
{
printf("%s\n",error);
return 0;
}

The following is lex code:

%{
#include<stdio.h>
#include "y.tab.h"
#define YYSTYPE double
extern int yylval;
%}
%%
[0-9]+|[0-9]*\.[0-9]+   { yylval=atof(yytext); return NUM;}
'\n'                    { return 0;}
'\t'                    {}
.                       {return yytext[0]; }
%%
int yywrap()
{
    return 1;
}

I compiled both lex and yacc code. There are no explicit errors except a few warnings. But when I run the executable file it shows no value but 0.000000.

Upvotes: 0

Views: 1026

Answers (1)

rici
rici

Reputation: 241721

#define YYSTYPE double
extern int yylval;

So which is the semantic type, int or double?

Since you use atof and printf("%g", $$), I suppose your intent is that the semantic type be floating point. But your declarations don't accomplish that:

  • Defining the macro YYSTYPE only has effect in the parser. The scanner never uses that macro. In the parser, the default type is int.

  • yylval is declared in the parser (as type YYSTYPE, according to the definitions in that file). So it is definitely an int and the extern declaration in the scanner is right, but undesired.

  • Using the format code %g to print an int is undefined behaviour. The fact that all numbers seem to print as 0.0 is not surprising, but then with UB no behaviour is surprising. This might be one of the warnings you are ignoring, if you even enabled compiler warnings when you compiled your parser. You should enable these warnings and take them seriously; that habit will help you solve your own problems.

Upvotes: 1

Related Questions