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)