I am making a basic calculator in Flex/Bison and I want to do exponentials (^) but my current implementation is not working, can anyone tell me why not and how to fix it?
%{
#include <stdio.h>
#include <math.h>
void yyerror(char *);
int yylex(void);
int symbol;
%}
%token INTEGER VARIABLE
%left '+' '-' '*' '/' '^'
%%
program:
program statement '\n'
| /* NULL */
;
statement:
expression { printf("%d\n", $1); }
| VARIABLE '=' expression { symbol = $3; }
;
expression:
INTEGER
| VARIABLE { $$ = symbol; }
| '-' expression { $$ = -$2; }
| expression '+' expression { $$ = $1 + $3; }
| expression '-' expression { $$ = $1 - $3; }
| expression '*' expression { $$ = $1 * $3; }
| expression '/' expression { $$ = $1 / $3; }
| expression '^' expression { $$ = $1 ^ $3; }
| '(' expression ')' { $$ = $2; }
;
%%
void yyerror(char *s) {
fprintf(stderr, "%s\n", s);
}
int main(void) {
yyparse();
}
Thanks
^
is not the exponential operator in C; it's xor. You need to use the math library function pow
or write your own integer exponentiation function.