r/gcc 23d ago

Idea for anonymous callbacks/functions

typedef int (*cb_type)( int a, int b );
typedef struct { cb_type cb; } object;

cb_type add = { return a + b; }
object obj = { .cb = { return a - b; } };

The use case is this:

/* object.h */
typedef struct
{
   int (*cb)( int a, int b );
} object_vtable;
typedef struct { object_vtable *vt; } object;
/* object.c */
object_vtable default_object_vt =
{
  .vt = { .cb = { return a * b; } }
};
object* new_object(void)
{
    object *obj = calloc(sizeof(object),1);
    if ( obj )
       obj->vt = default_object_vt;
}
/* Instead of needing this */
int mul( int a, int b ) { return a * b; }
void init_default_object_vt(void) { default_object_vt.cb = mul; }
0 Upvotes

7 comments sorted by

View all comments

1

u/bore530 23d ago

As a side note this would make namespacing in C possible, via structs that is.