Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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; 
like image 945
DCuser Avatar asked Sep 28 '12 15:09

DCuser


People also ask

Can you put a function inside a struct in C?

1. Member functions inside the structure: Structures in C cannot have member functions inside a structure but Structures in C++ can have member functions along with data members.

Can we define a function inside struct?

No, you cannot have functions inside struct in a C program.

Can we define function inside function in C?

Nested function is not supported by C because we cannot define a function within another function in C. We can declare a function inside a function, but it's not a nested function.


1 Answers

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; } 
like image 81
hmjd Avatar answered Oct 03 '22 17:10

hmjd