Search code examples
cdictionaryhashmap

Dictionary in C with functions as values


I'm making a game in alegro for a Uni project and wanted to use a dictinary or something like a hashmap to minimize the amount of ifs per action in the code and be able to implement some vary basic skin mechanics. Problem is I don't have any ideia how to implement such a thing. I've been using C for quite some time now, so I'm very confortable with dynamic memory allocation and controlling complex programs. Do you guys have any tips on how I can accomplish this?

The idea is to build a dictionary in which the keys are strings and the values are functions, so I can operate over the functions via indexing


Solution

  • As Barmar mentioned, you could utilize a hash table for mapping char* to function pointers if your functions have the same return types. If strings aren't strictly required in your case, you can get by with a simplified version of a hash table with macros.

    #define A 0
    #define B 1
    #define C 2
    
    void a() {}
    void b() {}
    void c() {}
    
    void (*funcs[3])() = {
        [A] = &a,
        [B] = &b,
        [C] = &c,
    };
    
    int main(int argc, char *argv[]) {
      (*funcs[B])();
      return 0;
    }