[英]What does this typedef declaration do?
I know what typedef does but this statement seems to be puzzling me. 我知道typedef可以做什么,但是这种说法似乎让我感到困惑。
typedef int (*funcptr)();
This declaration 这个宣言
funcptr pf1,pf2
Means this 意思是这个
int (*pf1)(),(*pf2)();
But then how to use pf1
and pf2
in program. 但是,然后如何在程序中使用pf1
和pf2
。 How to take input of these values. 如何输入这些值。 And what is the use of it. 以及它的用途是什么。
Your typedef
defines a type for a function pointer. 您的typedef
定义了函数指针的类型。 Taking a "value" of a function pointer has no meaning: it is a pointer to a piece of executable code; 取函数指针的“值”没有任何意义:它是一段可执行代码的指针。 you need to call it to make it useful. 您需要调用它以使其有用。
You call a function through a pointer in the same way as if it were a function known to you by name, ie by appending a parenthesized list of parameters to the pointer. 您可以通过指针调用函数,就像通过名称调用函数一样,即在指针后附加带括号的参数列表。
Here is what you can do with pf1
or pf2
: 这是您可以使用pf1
或pf2
:
// These functions return an int and take no parameters.
// They are compatible with funcptr
int function5() {
return 5;
}
int functionAsk() {
int res;
printf("Enter a value: ");
scanf("%d", &res);
return res;
}
// This function does not know what fp1 does, but it can use it
void doSomething(funcptr fp1) {
int res = fp1();
printf("Function returned %d", res);
}
// Here is how you can call doSomething with different function pointers
pf1 = functionAsk;
doSomething(pf1);
pf2 = function5;
doSomething(pf2);
Note how in the last four lines two calls of doSomething
perform different tasks based on what you pass: the first call prompts the user for an entry, while the second call returns five right away. 请注意,在最后四行中,两个doSomething
调用如何根据传递的内容执行不同的任务:第一个调用提示用户输入内容,而第二个调用立即返回五个。
This is a very artificial example code, but it illustrates how to use typedef
function pointers. 这是一个非常人为的示例代码,但是它说明了如何使用typedef
函数指针。
#include <stdio.h>
typedef int (*funcptr)();
int return1(void){return 1;}
int return2(void){return 2;}
int main()
{
funcptr pf1, pf2;
pf1 = return1;
pf2 = return2;
printf("%d, %d\n", pf1(), pf2());
return 0;
}
Output: 1, 2
输出: 1, 2
pf1和pf2现在是函数指针...如果希望它们指向函数,则应编写pf1 = yourfunctionname。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.