Lex and Yacc learn (eight) variable and tagged with type (extension calculator)

Source: Internet
Author: User

Variables and types of tags

The next step is to expand the calculator to handle variables with a single letter name, because there are only 26 letters (currently only in lowercase letters), so we can store variables in an array of 26 entries (called vbltable).

To make the calculator more useful, you can also extend it to handle multiple expressions (one per line) and use floating-point values.

Calculator lexical ch3-03.l with variables and real values

%{#include "ch3-03.tab.h" #include <math.h>extern double vbltable[26];%}%% ([0-9]+| ([0-9]*\. [0-9]+] ([ee][-+]?[ 0-9]+)?) {yylval.dval = Atof (yytext); return number;} [\t];/* ignores blank */[a-z]{yylval.vblno = yytext[0]-' a '; return NAME;} " $ "{return 0;/* Input end */}\n|. Return yytext[0];%%

Calculator syntax with variables and real values CH3-03.Y

%{double vbltable[26];%}%union {double dval;int vblno;} %token<vblno> name%token<dval>number%left '-' + '%left ' * '/'%nonassoc uminus%type <dval> Expression%%statement_list:statement ' \ n ' |statement_list statement ' \ n ' statement:name ' = ' expression{vbltable[$1] = $ 3; }|expression{printf ("=%g\n", $);}; Expression:expression ' + ' expression{$$ = $ + $;}| Expression '-' expression{$$ = $ $-$}| Expression ' * ' expression   {$$ = $ * $ $;}| Expression '/' expression{if ($ = = 0.0) Yyerror ("Divide by Zero"); else$$ = $/$3;}| ' -' expression%prec uminus {$$ =-$2;}| ' (' expression ') ' {$$ = $;}| number{$$ = $}| name{$$ = vbltable[$1];}; %%int Main () {yyparse (); return 0;} int Yyerror (char *s) {printf ("%s\n", s); return 0;}

Compiling run Results


Lex and Yacc learn (eight) variable and tagged with type (extension calculator)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.