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()?
The sum is stored into $$ so that it becomes the semantic value of the addition-expression just recognized by the rule. If there were a useful semantic value associated with the `+' token, it could be referred to as $2 . If you don't specify an action for a rule, Bison supplies a default: $$ = $1 .
The conversion value for 1 USD to 42.529 BISON.
Bison produces parser from the input file provided by the user. The function yylex() is automatically generated by the flex when it is provided with a . l file and this yylex() function is expected by parser to call to retrieve tokens from current/this token stream.
Bison is the GNU implementation/extension of Yacc, Flex is the successor of Lex. In either case, it's fine (and recommended) to use bison / flex. Additionally, byacc, the Berkeley implementation of yacc, is widely available (I see it in my Debian repository list).
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);} 
%%
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With