school

thing1's amazing school repo
Log | Files | Refs | Submodules | README

example.c (907B)


      1 #include <stdio.h>
      2 #include <stdlib.h>
      3 
      4 typedef enum op {
      5 	ADD,
      6 	SUB,
      7 	MUL,
      8 	DIV,
      9 } op;
     10 
     11 struct operation {
     12 	int a, b;
     13 	op o; 
     14 	int (*funcs[2][2])(int, int);
     15 };
     16 
     17 int add(int a, int b) {
     18 	return a + b;
     19 }
     20 int sub(int a, int b) {
     21 	return a - b;
     22 }
     23 int mul(int a, int b) {
     24 	return a * b;
     25 }
     26 int Div(int a, int b) {
     27 	return a / b;
     28 }
     29 
     30 int runop(struct operation *o) {
     31 	switch (o->o) {
     32 		case ADD: return o->funcs[0][0](o->a, o->b);
     33 		case SUB: return o->funcs[0][1](o->a, o->b);
     34 		case MUL: return o->funcs[1][0](o->a, o->b);
     35 		case DIV: return o->funcs[1][1](o->a, o->b);
     36 	}
     37 	return -1;
     38 }
     39 
     40 struct operation *initop(int a, int b, op ope) {
     41 	struct operation *o = malloc(sizeof(struct operation));
     42 	o->a = a;
     43 	o->b = b;
     44 	o->funcs[0][0] = &add;
     45 	o->funcs[0][1] = &sub;
     46 	o->funcs[1][0] = &mul;
     47 	o->funcs[1][1] = &Div;
     48 	o->o = ope;
     49 }
     50 
     51 int main() {
     52 	struct operation *o = initop(5, 5, MUL);
     53 	printf("%d\n", runop(o));
     54 }