6

I am using Flex/Bison/C++ to evaluate an expression Here is a sample bison file

string res; 
yy_scan_string(expression.c_str());               

yyparse();
cout<<"Result:"<<res<<"\n";
....
expr: expr PLUS expr { 
          $$=evaluate("+",$1,$3);
          res=$$;
          } 
     |expr MINUS expr { 
          $$=evaluate("-",$1,$3);
          res=$$;
          } 

Instead of using a variable res and storing the value in each action, is there a standard(like yylval) way to access the final result after yyparse()?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
yodhevauhe
  • 765
  • 3
  • 11
  • 33

1 Answers1

10

Yes.

Have a top level rule which just does the assignment:

%%
    toplev:   expr                    { res = $1; }
    expr:     expr PLUS expr          { $$=evaluate("+",$1,$3);}
           |  expr MINUS expr         { $$=evaluate("-",$1,$3);} 
%%
Martin York
  • 257,169
  • 86
  • 333
  • 562