0
votes

I am learning Bison/Flex and I do not understand how can I force the $$ type to be a float in .y file.

scanner.l file

%{
#include "token.h"
%}
%%
[0-9]+ { return TOKEN_INT; }
"/" { return TOKEN_DIV; }
%%
int yywrap() { return 1; }


parser.y file

%{
#include <stdio.h>
void yyerror(char const *s) {} ;
extern char *yytext;
%}

%token TOKEN_INT
%token TOKEN_DIV

%%
program : expr
    {
        float div_result;
        div_result=$1; 
        printf("In pgm %f \n",div_result);
    } ;
expr : factor TOKEN_DIV factor
    { 
        printf("In expr %f \n",(float)$1/(float)$3); 
        $$ = (float)$1 / (float)$3;
    } ;
factor: TOKEN_INT { $$ = atoi(yytext); } ;
%%

int main() { yyparse(); }

In expr rule, the printf output is right. For example, if the input is 7/3, the print output is 2.333333. But in program rule, the printf output is 2.000000.
It seems that $$ in expr rule or $1 in program rule is int type. Right ? and Why ?

1

1 Answers

1
votes

Because int is the default type for all semantic values unless you specify something else. See the bison manual for details.

As indicated in that link, it could be as simple as adding

%define api.value.type {double}

Don't use float. The "normal" floating point representation in C is double. float is far too imprecise to be useful for most purposes; it should only be used for very specific applications in which the imprecision is tolerable.