How to call the function using function pointer?

2019-01-22 07:11发布

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?

15条回答
迷人小祖宗
2楼-- · 2019-01-22 07:41
bool (*FuncPtr)()

FuncPtr = A;
FuncPtr();

If you want to call one of those functions conditionally, you should consider using an array of function pointers. In this case you'd have 3 elements pointing to A, B, and C and you call one depending on the index to the array, such as funcArray0 for A.

查看更多
Emotional °昔
3楼-- · 2019-01-22 07:42

Declare your function pointer like this:

bool (*f)();
f = A;
f();
查看更多
太酷不给撩
4楼-- · 2019-01-22 07:42

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();
查看更多
时光不老,我们不散
5楼-- · 2019-01-22 07:42

I usually use typedef to do it, but it may be overkill, if you do not have to use the function pointer too often..

//assuming bool is available (where I come from it is an enum)

typedef bool (*pmyfun_t)();

pmyfun_t pMyFun;

pMyFun=A; //pMyFun=&A is actually same

pMyFun();
查看更多
女痞
6楼-- · 2019-01-22 07:43

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 u 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 function 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]))();
查看更多
我想做一个坏孩纸
7楼-- · 2019-01-22 07:44

The best way to read that is The ``Clockwise/Spiral Rule''

By David Anderson

http://c-faq.com/decl/spiral.anderson.html

查看更多
登录 后发表回答