I am not new to C programming. But I don't understand why keeping a pointer to a function as a structure member is useful in C. Example:
// Fist Way: To keep pointer to function in struct
struct newtype{
int a;
char c;
int (*f)(struct newtype*);
} var;
int fun(struct newtype* v){
return v->a;
}
// Second way: Simple
struct newtype2{
int a;
char c;
} var2;
int fun2(struct newtype2* v){
return v->a;
}
int main(){
// Fist: Require two steps
var.f=fun;
var.f(&var);
//Second : simple to call
fun2(&var2);
}
Do programmers use it to give an Object-Oriented (OO) shape to their C code and provide abstract objects, or just to make code look technical?
I think that in the above code the second way is more gentle and pretty simple too. In the first way, we still have to pass &var, even though fun() is member of the struct.
If it's good to keep function pointers within a struct definition, kindly explain the reason.