How can I call a function using a function pointer?

前端 未结 16 1461
孤独总比滥情好
孤独总比滥情好 2020-12-02 17:24

Suppose I have these three functions:

bool A();
bool B();
bool C();

How do I call one of these functions conditionally using a function poi

相关标签:
16条回答
  • 2020-12-02 17:47

    You can do the following: Suppose you have your A,B & C function as the following:

    bool A()
    {
       .....
    }
    
    bool B()
    {
       .....
    }
    
    bool C()
    {
    
     .....
    }
    

    Now at some other function, say at main:

    int main()
    {
      bool (*choice) ();
    
      // now if there is if-else statement for making "choice" to 
      // point at a particular function then proceed as following
    
      if ( x == 1 )
       choice = A;
    
      else if ( x == 2 )
       choice = B;
    
    
      else
       choice = C;
    
    if(choice())
     printf("Success\n");
    
    else
     printf("Failure\n");
    
    .........
      .........
      }
    

    Remember this is one example for function pointer. there are several other method and for which you have to learn function pointer clearly.

    0 讨论(0)
  • 2020-12-02 17:49

    You can declare the function pointer as follows:

    bool (funptr*)();
    

    Which says we are declaring a function pointer to a function which does not take anything and return a bool.

    Next assignment:

    funptr = A;
    

    To call the function using the function pointer:

    funptr();
    
    0 讨论(0)
  • 2020-12-02 17:50
    //Declare the pointer and asign it to the function
    bool (*pFunc)() = A;
    //Call the function A
    pFunc();
    //Call function B
    pFunc = B;
    pFunc();
    //Call function C
    pFunc = C;
    pFunc();
    
    0 讨论(0)
  • 2020-12-02 17:52

    Initially define a function pointer array which takes a void and returns a void.

    Assuming that your function is taking a void and returning a void.

    typedef void (*func_ptr)(void);
    

    Now you can use this to create function pointer variables of such functions.

    Like below:

    func_ptr array_of_fun_ptr[3];
    

    Now store the address of your functions in the three variables.

    array_of_fun_ptr[0]= &A;
    array_of_fun_ptr[1]= &B;
    array_of_fun_ptr[2]= &C;
    

    Now you can call these functions using function pointers as below:

    some_a=(*(array_of_fun_ptr[0]))();
    some_b=(*(array_of_fun_ptr[1]))();
    some_c=(*(array_of_fun_ptr[2]))();
    
    0 讨论(0)
提交回复
热议问题