From: short <> Date: Mon, 9 Jul 2001 23:03:00 +0000 (+0000) Subject: Expression evaluation X-Git-Tag: rh71~80 X-Git-Url: https://git.jankratochvil.net/?p=nethome.git;a=commitdiff_plain;h=72e178bb813f10de7c23fb988564607292bec4e9;hp=c516a4d7f9783bba3b20adb4e5807fd94912c4db Expression evaluation --- diff --git a/src/ev.c b/src/ev.c new file mode 100644 index 0000000..f8f8d95 --- /dev/null +++ b/src/ev.c @@ -0,0 +1,130 @@ +#include +#include +#include +#include + +#define BUFSIZE 100 + +char *arg; + +int istack[BUFSIZE]; +char opstack[BUFSIZE]; +int istackp,opstackp; + +static char lex(int *ip) +{ +char c; +long l; + + while (isspace(*arg)) arg++; + switch (*arg) { + case 0: case '+': case '-': case '*': case '/': case '(': case ')': + c=*arg; + if (c) arg++; + return(c); + case '0' ... '9': + l=strtol(arg,&arg,10); + *ip=l; + return 'n'; + default: + fprintf(stderr,"Invalid characted in string: %s\n",arg); + exit(EXIT_FAILURE); + } +} + +static int oppri(char op) +{ + switch (op) { + case 0: return(0); + case '+': case '-': return (10); + case '*': case '/': return (20); + case '(': return (2); + case ')': return (5); + default: assert(0); + } +} + +static void evalit(void) +{ + assert(opstackp); + if (istackp<2) { + fprintf(stderr,"2 arguments for operator required!\n"); + exit(EXIT_FAILURE); + } + istackp--; + switch (opstack[--opstackp]) { + case '+': istack[istackp-1]+=istack[istackp]; break; + case '-': istack[istackp-1]-=istack[istackp]; break; + case '*': istack[istackp-1]*=istack[istackp]; break; + case '/': + if (!istack[istackp]) { + fprintf(stderr,"Division of %d by zero not supported!\n",istack[istackp-1]); + exit(EXIT_FAILURE); + } + istack[istackp-1]/=istack[istackp]; + break; + } +} + +static void pushop(char op) +{ +int mypri=oppri(op); + while (opstackp && op!='(' && oppri(opstack[opstackp-1])>=mypri) + evalit(); + if (!op) return; + if (op==')') { + if (!opstackp || opstack[opstackp-1]!='(') { + fprintf(stderr,"Not enough content for brackets-inside space!\n"); + exit(EXIT_FAILURE); + } + opstackp--; + return; + } + assert(opstackp