Get Flex/Bison action result
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=$$;
开发者_StackOverflow社区 }
|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()?
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);}
%%
精彩评论