handmade.network » Wiki » Using enum with function pointers in C

The thing I like about enum is that I can use them as a proxy to string. In the following example, we define the function pointer operate that gets one integer pointer and one integer as arguments. We define an enum that has INCR and DECR as members. Then we define a structure that has an array of the function pointer operate. This is kind of creating module in C. In the main program, we construct struct action Sact and we initialize it with two functions, i.e. increment and decrement. In the main program, instead of using index 0 or 1 to access these functions, we use enum members INCR and DECR. This makes it more clear what operation we are using.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include<stdio.h>
#include<stdlib.h>

typedef void (*operate)(int *, int);

void increment(int *, int);
void decrement(int *, int);

enum {
  INCR, DECR
};

struct action{

  operate act[2];
};

int main(void){

  int a = 5;

  struct action Sact = {{&increment,&decrement}};

  Sact.act[INCR](&a,1);
  printf("%d\n",a);
  Sact.act[DECR](&a,2);
  printf("%d\n",a);

  return 0;
}


void increment(int *a, int c){
  *a += c;
}

void decrement(int *a, int c){
  *a -= c;
}