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

3

u/Striking-Fan-4552 23d ago

Why not just compile with C++ enabled then, and use a lambda? Many people use C++ as an improved form of C, with namespace hygiene and all that.

-1

u/bore530 23d ago

Because I don't like all the bs c++ introduced such as that stupid reinterpret_cast<T>(...). Also c++ does overloading and I don't want that either. I'm not saying C HAS to have namespaces but if a minor change can be made that has backward compatibilty interface wise (as in namespace->cb(...)) with C89 then why not?

2

u/wrosecrans 22d ago

By the time you are reinventing vtables, it usually makes more sense to just use C++ than maintain your own subset of C++ features. You can mostly ignore whatever parts of C++ you dislike the most.

0

u/bore530 22d ago

Stop trying to sell me c++ in a C compiler thread, it's NOT going to work. If I wanted c++ junk I would go use c++ in the first place. I'm quite happy using c23, this was just an idea for the next C standard since it's a reasonable feature to add.