Can we define functions in structs in C programming language?
No, but you can in c++ struct!
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.
No, you can't. Structs can only contain variables inside, storing function pointers inside the struct can give you the desired result.
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);
}