Suppose I have these three functions:
bool A();
bool B();
bool C();
How do I call one of these functions conditionally using a function pointer, and how do I declare the function pointer?
Suppose I have these three functions:
bool A();
bool B();
bool C();
How do I call one of these functions conditionally using a function pointer, and how do I declare the function pointer?
your choice is stored in a; Then accordingly, functions are assigned in the function pointer. Finally depending on your choice, the very same function is called to return the desired result.
You can do the following: Suppose you have your A,B & C function as the following:
Now at some other function, say at main:
Remember this is one example for function pointer. there are several other method and for which you have to learn function pointer clearly.
If you need help with complex definitions, like what is:
Take a look at my Right-Left Rule here.
Note that when you say:
you are declaring
a
of type "pointer to function returningbool
and taking an unspecified number of parameters". Assumingbool
is defined (maybe you're using C99 and have includedstdbool.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()
, andC()
are all declared as functions "returningbool
and taking an unspecified number of parameters".To see the kind of problems that may have, let's write a program:
When I compile the above with gcc, it says:
for the line
b = test_one;
, which is good. There is no warning for the corresponding assignment toa
.So, you should declare your functions as:
And then the variable to hold the function should be declared as:
I think your question has already been answered more than adequately, but it might be useful to point out explicitly that given a function pointer
the two calls
are exactly equivalent in every way by definition. The choice of which to use is up to you, although it's a good idea to be consistent. For a long time, I preferred
(*pf)(1, 0)
because it seemed to me that it better reflected the type ofpf
, however in the last few years I've switched topf(1, 0)
.You declare a function pointer variable for the given signature of your functions like this:
you can assign it one of your functions:
and you can call it:
You might consider using typedefs to define a type for every distinct function signature you need. This will make the code easier to read and to maintain. i.e. for the signature of functions returning bool with no arguments this could be:
and then you can use like this to declare the function pointer variable for this type: