Search code examples
cfunctionstruct

C - function inside struct


Im trying to assign a function inside a struct, so far I have this code:

typedef struct client_t client_t, *pno;
struct client_t
{
    pid_t pid;
    char password[TAM_MAX]; // -> 50 chars
    pno next;
    
    pno AddClient() 

    {
        /* code */
    }
};

int main()
{
    client_t client;

    // code ..

    client.AddClient();
}
**Error**: *client.h:24:2: error: expected ‘:’, ‘,’, ‘;’, ‘}’ or ‘__attribute__’ before ‘{’ token.*

Which is the correct way to do it ?


Solution

  • It can't be done directly, but you can emulate the same thing using function pointers and explicitly passing the "this" parameter:

    typedef struct client_t client_t, *pno;
    struct client_t
    {
        pid_t pid;
        char password[TAM_MAX]; // -> 50 chars
        pno next;
    
        pno (*AddClient)(client_t *); 
    };
    
    pno client_t_AddClient(client_t *self) { /* code */ }
    
    int main()
    {
    
        client_t client;
        client.AddClient = client_t_AddClient; // probably really done in some init fn
    
        //code ..
    
        client.AddClient(&client);
    
    }
    

    It turns out that doing this, however, doesn't really buy you an awful lot. As such, you won't see many C APIs implemented in this style, since you may as well just call your external function and pass the instance.