I'm currently working on a dictionary library in C and would like to start using struct's for easy assignment. Now, I have several functions that need to be a member in said struct's. I have it working well using pointers, but my only problem is that I would like to not have to assign the function to the pointer in every instance. For instance;

int func(int a)
{
    return a;
}

int main()
{
    struct foo
    {
        int (*func)(int)
    };
    struct foo bar;
    bar.func = func; /* This is the part I'd like to get rid of. I'd like it to just be '
                        bar.func(4), for instance' */
    bar.func(4);
return 0;
}

So is it possible to assign the struct pointer _to_ the function? Or does it have to be assigned after the new variable is initialized? I'm not exactly too sure on how to go about that, so anything would help!

Thanks!

The function pointer in the structure is a data member of the structure just like any other data member and can be initialized like so

struct foo bar = { func };

But you are always either going to have to explicitly initialize it or assign it.

The way Banfa suggests is a common way to do this. Macros are another way you will see. Something like

#define MAKE_COMMON_FOO(f,fun) struct foo f; \
   f.func = fun

Which would be used like

MAKE_COMMON_FOO(bar,func);
bar.func(4);

The advantage of the macro is that as the struct evolves the changes to the code that uses the struct are centralized.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.