Can I define a function inside a C structure? [duplicate]

I am trying to convert some C++ code to C and I am facing some problems. How can I define inside a structure a function?

Like this:

 typedef struct  {
    double x, y, z;
    struct Point *next;
    struct Point *prev;
    void act() {sth. to do here};
} Point;

Solution 1:

No, you cannot define a function within a struct in C.

You can have a function pointer in a struct though but having a function pointer is very different from a member function in C++, namely there is no implicit this pointer to the containing struct instance.

Contrived example (online demo http://ideone.com/kyHlQ):

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

struct point
{
    int x;
    int y;
    void (*print)(const struct point*);
};

void print_x(const struct point* p)
{
    printf("x=%d\n", p->x);
}

void print_y(const struct point* p)
{
    printf("y=%d\n", p->y);
}

int main(void)
{
    struct point p1 = { 2, 4, print_x };
    struct point p2 = { 7, 1, print_y };

    p1.print(&p1);
    p2.print(&p2);

    return 0;
}

Solution 2:

You can have a function pointer in a struct though. but not in this way

you can define it in this way

example:

typedef struct cont_func 
{
    int var1;
    int (*func)(int x, int y);
    void *input;
} cont_func;


int max (int x, int y)
{
    return (x > y) ? x : y;
}

int main () {
   struct cont_func T;

   T.func = max;
}

Solution 3:

In C it is not allowed to define a method inside a struct. You could define a function pointer inside a struct as follows:

typedef struct  {
  double x, y, z;
  struct Point *next;
  struct Point *prev;
  void (*act)();
} Point;

You will have to assign the pointer to a specific function whenever you instantiate the struct.

Solution 4:

No, it is not possible to declare a function inside a struct in C.

That is (one of) the fundamental differences between C and C++.

See this thread: https://web.archive.org/web/20121024233849/http://forums.devshed.com/c-programming-42/declaring-function-in-structure-in-c-545529.html