Get Flex / Bison Action Result

I use Flex / Bison / C ++ to evaluate an expression. Here is an example 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 the res variable and storing the value in each action, is there a standard (e.g. yylval) way to get the final result after yyparse ()?

+6
c ++ flex-lexer bison
source share
1 answer

Yes.

You have a top-level rule that just does the assignment:

 %% toplev: expr { res = $1; } expr: expr PLUS expr { $$=evaluate("+",$1,$3);} | expr MINUS expr { $$=evaluate("-",$1,$3);} %% 
+7
source share

All Articles