I am not new to C programming. But I don't understand what is usefulness to keep pointer to function as a structure member in C. e.g.
// 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);
}
Does programmers use it to give Object Oriented(OO) shape to there C code and provide abstract object? Or to make code look technical.
I think, in above code second way is more gentle and pretty simple too. In fist way, we still have to pass &var
, even fun()
is member of struct.
If its good to keep function pointer within struct definition, kindly help to explain the the reason.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…