Can we have functions in structures in C language?
Could someone please give an example of how to implement it and explain?

- 16,404
- 12
- 44
- 69
-
4No, but structure could contain a pointer to function (this leaves initialisation to you, of course). – keltar Jun 20 '14 at 09:53
-
Look up function pointers. – PandaConda Jun 20 '14 at 09:53
-
4http://stackoverflow.com/questions/17052443/c-function-inside-struct 1 second in google – timgeb Jun 20 '14 at 09:54
-
1What would be the point of having functions (executable instructions) as part of a structure? Would an array of such structure have multiple copies of the functions? What would the sizeof operator yield for such a struct? – Jens Jun 20 '14 at 10:46
3 Answers
No, structures contain data only. However, you can define a pointer to a function inside of a struct as below:
struct myStruct {
int x;
void (*anotherFunction)(struct foo *);
}

- 8,584
- 8
- 45
- 46
The answer is no, but there is away to get the same effect.
Functions can only be found at the outermost level of a C program. This improves run-time speed by reducing the housekeeping associated with function calls.
As such, you cannot have a function inside of a struct (or inside of another function) but it is very common to have function pointers inside structures. For example:
#include <stdio.h>
int get_int_global (void)
{
return 10;
}
double get_double_global (void)
{
return 3.14;
}
struct test {
int a;
double b;
};
struct test_func {
int (*get_int) (void);
double (*get_double)(void);
};
int main (void)
{
struct test_func t1 = {get_int_global, get_double_global};
struct test t2 = {10, 3.14};
printf("Using function pointers: %d, %f\n", t1.get_int(), t1.get_double());
printf("Using built-in types: %d, %f\n", t2.a, t2.b);
return 0;
}
A lot of people will also use a naming convention for function pointers inside structures and will typedef their function pointers. For example you could declare the structure containing pointers like this:
typedef int (*get_int_fptr) (void);
typedef double (*get_double_fptr)(void);
struct test_func {
get_int_fptr get_int;
get_double_fptr get_double;
};
Everything else in the code above will work as it is. Now, get_int_fptr is a special type for a function returning int and if you assume that *_fptr are all function pointers then you can find what the function signature is by simply looking at the typedef.

- 11,159
- 21
- 74
- 121
No, it has to be implemented like this :
typedef struct S_House {
char* name;
int opened;
} House;
void openHouse(House* theHouse);
void openHouse(House* theHouse) {
theHouse->opened = 1;
}
int main() {
House myHouse;
openHouse(&myHouse);
return 0;
}

- 51
- 1
- 2