2

First of all I am not a C expert but I thought I'd be able to break down C code. I am currently reading some open source repo and have no idea what the following statement within some struct in a header file means:

struct some_struct{
   ... 
   /* Callback when non-reply message comes in (inside db transaction) */
   void (*billboardcb)(void *channel, bool perm, const char *happenings);
   ...
} 

I thought functions cannot be declared like methods within structs. But if this is a variable (called billboardcb) why are there all these paremeters? I did not find a macro called billboardcb in this code base.

Alex Johnson
  • 958
  • 8
  • 23
Rene Pickhardt
  • 692
  • 5
  • 17

2 Answers2

2

A function pointer is a pointer that stores an address to a function. Function pointers can live inside structs just like any other pointer. The (void *channel, bool perm, const char *happenings) parameters listed after void (*billboardcb) are the function's parameters. The void preceding the (*billboardcb) pointer indicates that the function returns nothing.

If you search for where the some_struct struct is instantiated, you'll likely find the actual function assigned to this pointer. The function assigned to the pointer will be declared like any other function, with its address then stored in the struct by assigning the function's memory address to the struct's pointer.

1

It's a pointer to function, the function pointer is called billboardcb. The pointer can only point to a function with the 3 parameters that are:

1) void* 2) bool 3) const char *

The pointer can be assigned by just giving it an address of another function with compatible format.

Owl
  • 1,446
  • 14
  • 20