Search code examples
cfunction-pointers

"this" pointer in C (not C++)


I'm trying to create a stack in C for fun, and came up with the idea of using struct to represent the stack. Then I add function pointers to the struct for push() and pop() operations.

So far all is good it seems, but, for the implementation of the push() and pop() functions I need to refer to *this somehow. How can that (can it?) be done?

This is my struct

struct Stack {
    int *data;
    int current_size;
    int max_size;
    int (*push)(int);
    int (*pop)();
};

And as an example here's push

int push(int val) {
    if(current_size == max_size -1)
            return 0;

    data[current_size] = val;
    current_size++;

    return 1;
}

As you can imagine, the compiler has no idea what current_size is, as it would expect something like stack->current_size.

Is this possible to overcome somehow?


Solution

  • There's no implicit this in C. Make it explicit:

    int push(Stack* self, int val) {
        if(self->current_size == self->max_size - 1)
                return 0;
    
        self->data[self->current_size] = val;
        (self->current_size)++;
    
        return 1;
    }
    

    You will of course have to pass the pointer to the struct into every call to push and similar methods.

    This is essentially what the C++ compiler is doing for you when you define Stack as a class and push et al as methods.