/* * this file contains the functions that do the arithmetic/math calculations * * to add a function do the following: * 1. decide on a *single* character to invoke it * 2. write the function and put a prototype under the ones already there * 3. add to the table the character to invoke it and the function to do it * (note this ltter is done by giving the function pointer) * * all functions operate using the stack, so no parameters needed */ #include #include "stack.h" /* * protptypes */ void add(void); void subtract(void); void multiply(void); /* * the switching table */ struct tbl { char op; /* single char operator */ void (*func)(); /* address of function to be invoked */ } fnarray[] = { { '+', add }, { '-', subtract }, { '*', multiply }, { '\0', NULL }, }; /* * the switching function * it takes the one-character operator and calls the associated function */ void fnswitch(char oper) { struct tbl *e; /* pointer to table entries */ /* * loop through the table until you either find the * function or you reach the end */ for(e = fnarray; e->op != '\0'; e++){ if (e->op == oper){ /* got it! run the associated function */ (e->func)(); return; } } /* * if you get here there was no corresponding function * so complain */ fprintf(stderr, "%c: no such operation\n", oper); } /* * pop the top two numbers off the stack, add them, and * push the result onto the stack */ void add(void) { int v1, v2; /* values that are popped */ /* pop the top 2 elements */ if (pop(&v1) == 0) return; if (pop(&v2) == 0) return; /* add them and push it back onto the stack */ push(v2 + v1); } /* * pop the top two numbers off the stack, subtract them, and * push the result onto the stack */ void subtract(void) { int v1, v2; /* values that are popped */ /* pop the top 2 elements */ if (pop(&v1) == 0) return; if (pop(&v2) == 0) return; /* subtract them and push it back onto the stack */ push(v2 - v1); } void multiply(void) { int v1, v2; /* values that are popped */ /* pop the top 2 elements */ if (pop(&v1) == 0) return; if (pop(&v2) == 0) return; /* multiply them and push it back onto the stack */ push(v2 * v1); }