How can I call a function using a function pointer?

前端 未结 16 1636
孤独总比滥情好
孤独总比滥情好 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.

提交回复
热议问题