How can I call a function using a function pointer?

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

    Note that when you say:

    bool (*a)();
    

    you are declaring a of type "pointer to function returning bool and taking an unspecified number of parameters". Assuming bool is defined (maybe you're using C99 and have included stdbool.h, or it may be a typedef), this may or may not be what you want.

    The problem here is that there is no way for the compiler to now check if a is assigned to a correct value. The same problem exists with your function declarations. A(), B(), and C() are all declared as functions "returning bool and taking an unspecified number of parameters".

    To see the kind of problems that may have, let's write a program:

    #include 
    
    int test_zero(void)
    {
        return 42;
    }
    
    static int test_one(char *data)
    {
        return printf("%s\n", data);
    }
    
    int main(void)
    {
        /* a is of type "pointer to function returning int
           and taking unspecified number of parameters */
        int (*a)();
    
        /* b is of type "pointer to function returning int
           and taking no parameters */
        int (*b)(void);
    
        /* This is OK */
        a = test_zero;
        printf("a: %d\n", a());
    
        a = test_one; /* OK, since compiler doesn't check the parameters */
        printf("a: %d\n", a()); /* oops, wrong number of args */
    
        /* This is OK too */
        b = test_zero;
        printf("b: %d\n", b());
    
        /* The compiler now does type checking, and sees that the
           assignment is wrong, so it can warn us */
        b = test_one;
        printf("b: %d\n", b()); /* Wrong again */
    
        return 0;
    }
    

    When I compile the above with gcc, it says:

    warning: assignment from incompatible pointer type

    for the line b = test_one;, which is good. There is no warning for the corresponding assignment to a.

    So, you should declare your functions as:

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

    And then the variable to hold the function should be declared as:

    bool (*choice)(void);
    

提交回复
热议问题