Skip to content
Snippets Groups Projects
Select Git revision
  • 8e60d9ec9649fafdbab260dfc11647d1b4065ef1
  • 2024ss default
  • 2023ss
  • 2022ss
  • 2021ss protected
5 results

calls-01.c

Blame
  • objects-10.c 1.21 KiB
    #include <stdio.h>
    #include <stdlib.h>
    
    #define T_BASE    0
    #define T_INTEGER 1
    #define T_STRING  2
    
    typedef struct
    {
      int type;
      void (* print) (t_object *this);
    } t_base;
    
    typedef struct
    {
      int type;
      void (* print) (t_object *this);
      int content;
    } t_integer;
    
    typedef struct
    {
      int type;
      void (* print) (t_object *this);
      char *content;
    } t_string;
    
    typedef union
    {
      t_base base;
      t_integer integer;
      t_string string;
    } t_object;
    
    void print_integer (t_object *this)
    {
      printf ("Integer: %d\n", this->integer.content);
    }
    
    void print_string (t_object *this)
    {
      printf ("String: \"%s\"\n", this->string.content);
    }
    
    t_object *new_integer (int i)
    {
      t_object *p = malloc (sizeof (t_integer));
      p->integer.type = T_INTEGER;
      p->integer.print = print_integer;
      p->integer.content = i;
      return p;
    }
    
    t_object *new_string (char *s)
    {
      t_object *p = malloc (sizeof (t_string));
      p->string.type = T_STRING;
      p->string.print = print_string;
      p->string.content = s;
      return p;
    }
    
    int main (void)
    {
      t_object *object[] = { new_integer (42),
                             new_string ("Hello, world!"),
                             NULL };
    
      for (int i = 0; object[i]; i++)
        object[i]->base.print (object[i]);
    
      return 0;
    }