daniel
daniel

Reputation: 221

C - Can I define a default function pointer in a struct?

struct Point
{
    int x;
    void(*func)(struct Point*, int);
};

void addToX(struct Point* a, int b) {
    a->x += b;
}

void main() {
    struct Point p1;
    p1.x = 3;
    p1.func = &addToX;

    printf("%d\n", p1.x);

    p1.func(&p1, 2);
    printf("%d\n", p1.x);
}

In the code above, we have an object Point, which contains x and a function.

When I'm making a Point, I need to initialize x and the pointer to the function.

This is pretty bad as I don't want to initialize the function pointer every time!

Is there a way to define it, so that every time I create a new Point it will automatically point to addToX?

Upvotes: 2

Views: 821

Answers (3)

technosaurus
technosaurus

Reputation: 7802

The easiest way to do it is to have a default struct that you can copy.

const struct​ foo default_foo = {
    .func = myfunc;
};

Later you can just initialize a new struct foo to the default.

struct foo local_foo = default_foo;

You could even have other versions for common use cases.

Upvotes: 2

CookiePLMonster
CookiePLMonster

Reputation: 205

I'm pretty sure the answers to your problem are called class and C++. Is there any particular reason you are sticking to plain C?

EDIT: Since you said it's for an uni project: no, you cannot initialize it "automatically". The best solution I could think of is to define something like:

struct Point
{
    int x;
    void(*func)(struct Point*, int);
};

void addToX(struct Point*a, int b) {
    a->x +=b;
}

void point_init(struct Point* a) {
    a->func = &addToX;
}

void main() {
    struct Point p1;
    point_init(&p1);
    p1.x = 3;

    printf("%d\n", p1.x);

    p1.func(&p1, 2);
    printf("%d\n", p1.x);
}

Upvotes: 1

hyde
hyde

Reputation: 62797

If you want to have some default values, you need to create constructor function. Something like this:

struct Point createPoint(int x) {
    struct Point r = { x, addToX };
    return r;
}

And then just use it like this:

struct Point p1 = createPoint(3);

Alternatively, you could create default value as a macro:

#define POINT_INITIALIZER(x) { (x), addToX }

Used like:

struct Point p1 = POINT_INITIALIZER(3);

I would recommend function, because they are more safe, and I don't see any advantage the macro would give.

Upvotes: 2

Related Questions