Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
788 views
in Technique[技术] by (71.8m points)

oop - How pointers to function as struct member useful in C?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...