Search code examples
coopstructcoding-stylestructure

How are pointers to functions as struct members useful in C?


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.


Solution

  • 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.