title: Ways to illicit polymorphic properties in regular C?
body: <p>Hi I am currently attempting to learn C and I was wondering if there is a way to attain polymorphism in structures which contain a list of other different type of structures?</p>
  
  <p>An example case of this is as such:</p>
  
  <pre><code>  #include &lt;stdlib.h&gt;
  #include &lt;stdio.h&gt;
  
  typedef void (*update_t)(void *);
  
  typedef struct entity entity_t;
  typedef struct compA compA_t;
  typedef struct compB compB_t;
  
  
  struct compA{
  
      update_t update;
  };
  
  struct compB{
  
      update_t update;
  };
  
  struct entity{
      update_t update;
      int curSize;
      void **components;
  };
  
  
  void compA_update(void *c){
      printf("updating: componentA\n");
  }
  
  compA_t *compA_create(){
      compA_t *c = malloc(sizeof(compA_t));
      c-&gt;update = compA_update;
      return c; 
  }
  
  void compB_update(void *c){
      printf("updating: componentB\n");
  }
  
  
  compB_t *compB_create(){
      compB_t *c = malloc(sizeof(compB_t));
      c-&gt;update = compB_update;
      return c; 
  }
  
  
  void entity_update(void *en){
      entity_t *e = (entity_t *)en;
      for(int i = 0; i &lt; e-&gt;curSize; i++){
          //would like to somehow update all the components with one line just iterating through the array but does not seem possible
      }
      return;
  }
  
  
  
  entity_t *entity_create(){
      entity_t *e = malloc(sizeof(entity_t));
      e-&gt;curSize = 0;
      e-&gt;update = entity_update;
      calloc(32, sizeof(void *));
      return e;
  }
  
  void add_component(entity_t *e, void *c){
      printf("%d\n", e-&gt;curSize);
      e-&gt;components[e-&gt;curSize] = c;
      e-&gt;curSize++;
      return;
  }
  
  
  
  
  int main(void){
  
      entity_t *e = entity_create();
      compA_t *a = compA_create();
      compB_t *b = compB_create();
      add_component(e, a);
      add_component(e, b);
  
      e-&gt;update(e);
  
      return 0;
  }
  </code></pre>
  
  <p>So far my approach to this problem has been solved with void pointer arrays of a tuple structure which contains a enum type which identifies the structure as well as the structure itself and then in a potential update function a fairly ugly switch statement has to be implemented with a case for each specific type.</p>
  
  <p>Is there a better way to do this? As the switch approach will get fairly crazy pretty fast if there are a lot of different types within the array. which means one must explicitly add cases for each type and every case does exactly the same thing, which in this case is call a function pointer named "update".</p>