In the main() function of the following code, I wrote a very naive command parsing. Is there any more efficient way?
This program is aim to deal with ADD, SUB, MUL, DIV these four arithmetic operations for integers. The input would be in form like: ADD 1 1, MUL 12 90. And also there would be a special input character % which means use the last result. For example, ADD 1 1 would return 2, then ADD % 1 would return 3.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef int (*calc_function)(int, int);
typedef struct operation {
char *name;
calc_function calculate;
} Operation;
int add(int a, int b) { return a+b; }
int sub(int a, int b) { return a-b; }
int mul(int a, int b) { return a*b; }
int divi(int a, int b) { return a/b; }
int calc(int a, int b, int (*c)(int, int)) {
return c(a, b);
}
int main() {
char *command = malloc(9);
int result = 0;
int a;
int b;
Operation ADD = {"ADD", add};
Operation SUB = {"SUB", sub};
Operation MUL = {"MUL", mul};
Operation DIV = {"DIV", divi};
Operation ops[4] = {ADD, SUB, MUL, DIV};
while((command = fgets(command, 9, stdin)) != NULL) {
for(int i = 0; i < 4; ++i) {
if (0 == strncmp(ops[i].name, command, 3)) {
command = strchr(command, ' ');
command++;
if (*command == '%') {
a = result;
} else {
sscanf(command, "%d", &a);
}
command = strchr(command, ' ');
command++;
if (*command == '%') {
b = result;
} else {
sscanf(command, "%d", &b);
}
result = ops[i].calculate(a, b);
printf("%d\n", result);
}
}
}
free(command);
return 0;
}
Also, any advice on improving the performence and style of this program would be highly appreciated!