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.
To access members of a structure using pointers, we use the -> operator. In this example, the address of person1 is stored in the personPtr pointer using personPtr = &person1; . Now, you can access the members of person1 using the personPtr pointer.
Pointer to structure holds the add of the entire structure. It is used to create complex data structures such as linked lists, trees, graphs and so on. The members of the structure can be accessed using a special operator called as an arrow operator ( -> ).
//function pointer use to display message typedef void (*pfnMessage)(const char*,float fResult); //function pointer use to perform arithmetic operation typedef float (*pfnCalculator)(float,float); Step-2: Now create a structure template as your requirement.
Function pointers can be stored in variables, structs, unions, and arrays and passed to and from functions just like any other pointer type. They can also be called: a variable of type function pointer can be used in place of a function name.
Providing a pointer to function on a structure can enable you to dynamically choose which function to perform on a structure.
struct newtype{
int a;
int b;
char c;
int (*f)(struct newtype*);
} var;
int fun1(struct newtype* v){
return v->a;
}
int fun2(struct newtype* v){
return v->b;
}
void usevar(struct newtype* v) {
// at this step, you have no idea of which function will be called
var.f(&var);
}
int main(){
if (/* some test to define what function you want)*/)
var.f=fun1;
else
var.f=fun2;
usevar(var);
}
This gives you the ability to have a single calling interface, but calling two different functions depending on if your test is valid or not.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With