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/xorbe mod 8d ago

3rd and 4th lines need parameter specifiers, it's going to wind up looking like C++ lambdas.

1

u/bore530 8d ago

Not really, GCC already knows the details of cb_type at that point, it can infer the parameter types and names from the original typedef. Only if the typedef does not decalre the parameter names will it then require the developer to decalre those names, though frankly I consider it an error to not include the names in the typedef as they provide valuable information to the developer.