Can we define functions in structs in C programming language?
-
4Do you mean something like struct A { void f(void) {...} }; ? – tchap Mar 26 '12 at 11:24
10 Answers
No, as functions are not data. But you can define function pointers inside a struct.
struct foo {
int a;
void (*workwithit)(struct foo *);
}

- 35,956
- 47
- 141
- 220

- 89,107
- 13
- 149
- 217
You can't really declare stuff inside of a struct in C. This is not C++ or any other OO language where an object encapsulates some kind of scope.
C structs are very simple objects, it's just syntactic sugar for managing a piece of memory. When you create new struct "instance", struct A a;
, compiler just reserves stack space according to its size, and when you then do a.member
, compiler knows that member's offset, so it jumps to &a
+ offset of that member. Those offsets are usually not just sums of sizes of preceding members, because compiler usually adds some padding bits into the structure to align it nicer into memory.
Hope it helped a bit. You obviously expect slightly too much from C stuctures :-)

- 1,047
- 8
- 10
I came to this post because I was looking for a way to teach a bit of Object Oriented "style" of programming in C for a very simple data structures course. I did not want to teach C++ because I did not want to keep explaining its more advanced features.
But I wanted to explore how one might implement the OO pattern used in Python but in a low-level language / run-time. By explaining what is going on in C, students might better understand the Python OO run-time patterns. So I went a bit beyond the first answer above and adapted some of the patterns from https://stackoverflow.com/a/12642862/1994792 but in a way that would elucidate OO run time patterns a bit.
First I made the "class" with a "constructor" in point.c:
#include <stdio.h>
#include <stdlib.h>
struct point
{
int x;
int y;
void (*print)(const struct point*);
void (*del)(const struct point*);
};
void point_print(const struct point* self)
{
printf("x=%d\n", self->x);
printf("y=%d\n", self->y);
}
void point_del(const struct point* self) {
free((void *)self);
}
struct point * point_new(int x, int y) {
struct point *p = malloc(sizeof(*p));
p->x = x;
p->y = y;
p->print = point_print;
p->del = point_del;
return p;
}
Then I imported the class, constructed an object from the class, used the object, then destructed the object in main.c
#include "point.c"
int main(void)
{
struct point * p3 = point_new(4,5);
p3->print(p3);
p3->del(p3);
}
It feels very "Pythonic in C".

- 4,415
- 3
- 27
- 30
-
2This is really enlightening, I feel like I found an easter egg. This should have more upvotes! – tgabb Dec 16 '20 at 23:17
-
-
@drchuck I agree with tgabb that your post is great! It helped me a lot. Kudos! – Roger Costello Apr 09 '21 at 18:15
-
@tgabb - the free() function expects a (void *) as its parameter. So I am trying to avoid any warning messages. – drchuck Apr 11 '21 at 15:14
No, you cannot have functions inside struct in a C program. I wrote a single code and saved that as a .c and a .cpp. The .cpp file complies and works as expected, but the .c file doesn't even compile.
Here is the code for your reference. Save it once as .cpp and then run it. Then save the same code as .c and compile it. You will get a compilation errors.
#include <stdio.h>
struct C {
void Test(int value) {
static int var = 0;
if (var == value)
printf("var == value\n");
else
printf("var != value\n");
var = value;
}
};
int main() {
C c1;
C c2;
c1.Test(100);
c2.Test(100);
int ii;
scanf("%d",&ii);
}

- 1,659
- 4
- 26
- 45
-
1Since when it is not possible to have **functions** inside **C** program? – baldrs Nov 14 '16 at 12:05
-
-
No.
You can have function pointers in structs, but that's as close as you'll get.

- 202,337
- 40
- 393
- 406
No, you can't. Structs can only contain variables inside, storing function pointers inside the struct can give you the desired result.

- 4,623
- 5
- 30
- 33
You can in C++ instead:
// Example program
#include <iostream>
#include <string>
struct Node
{
int data; Node *prev,*next;
Node(int x, Node* prev=NULL, Node* next=NULL)
{
this->data=x; this->prev=prev; this->next=next;
}
void print_list()
{
Node* temp=this; //temp is created in function call stack
while(temp!=NULL)
{
std::cout<<temp->data<<" ";
temp=temp->next;
}
}
Node* insert_left(int x)
{
Node* temp=new Node(x,this->prev,this);
this->prev=temp;
return temp; //list gets new head
}
Node* insert_right(int x)
{
Node* temp=new Node(x,this,this->next);
this->next=temp;
return this; //this would still be head
}
};
int main()
{
Node* head=new Node(-1); //-1
head=head->insert_left(0); //0 -1
head=head->insert_right(1); //0 1 -1
head=head->insert_left(2); //2 0 1 -1
head->print_list();
}

- 198
- 1
- 11
You can use only function pointers in C. Assign address of real function to that pointer after struct initialization, example:
#include <stdio.h>
#include <stdlib.h>
struct unit
{
int result;
int (*add) (int x, int y);
};
int sumFunc(int x, int y) { return x + y; }
void *unitInit()
{
struct unit *ptr = (struct unit*) malloc(sizeof(struct unit));
ptr->add = &sumFunc;
return ptr;
}
int main(int argc, char **argv)
{
struct unit *U = unitInit();
U->result = U->add(5, 10);
printf("Result is %i\n", U->result);
free(U);
return 0;
}
Good example of using function pointers in a struct you can find here https://github.com/AlexanderAgd/CLIST Check header and then clist.c file.

- 11
- 2
No, You cant define functions inside structures in C programs, However if the extension of your file is .cpp (that is not C), you can have member functions like classes however the default modifier of these functions will be 'public'(unlike class).
Read these links for more information on Structures a good link , another good link, One more good link
As a convention in C++, Classes are used for storing functions and variables both and Structures are used only for storing information (i.e. data).

- 13,134
- 17
- 77
- 148
-
5What you probably meant is: "However, if you compile this in a different programming language called C++..." – Lundin Mar 26 '12 at 11:33
-
You are right @Lundin, Actually at starting level few students confuse themselves by writing C code inside .cpp file, that is really a bad practice. – Amit Mar 26 '12 at 11:49