typedef int (*pf) needs explaining

笑着哭i 提交于 2019-11-30 13:48:33

问题


Generally, we use typedef to get alternate names for datatypes. For example --

typedef long int li; // li can be used now in place of long int

But, what does the below typedef do?

typedef int (*pf) (int, int);

回答1:


typedef int (*pf) (int, int);

This means that variables declared with the pf type are pointers to a function which takes two int parameters and returns an int.

In other words, you can do something like this:

#include <stdio.h>

typedef int (*pf)(int,int);

int addUp (int a, int b) { return a + b; }

int main(void) {
    pf xyzzy = addUp;
    printf ("%d\n", xyzzy (19, 23));
    return 0;
}



回答2:


typedef long int li;

assigns alternate name li to type long int.

In exactly the same way

typedef int (*pf) (int, int);

assigns alternate name pf to type int (*) (int, int). That all there is to it.

As you probably noticed, typedef declarations follow the same syntax as, say, variable declarations. The only difference is that the new variable name is replaced by the new type name. So, in accordance with C declaration syntax, the declared name might appear "in the middle" of the declarator, when array or function types are involved.

For another example

typedef int A[10];

declares A as alternate name for type int [10]. In this example the new name also appears "in the middle" of the declaration.




回答3:


It's a function pointer prototype. You can then declare a function as an argument something like this:

void RegisterCallback(pf your_callback_func);

Then you can can call the function passed as a func ptr:

...
your_callback_func(i, j);
...



回答4:


The typedef has the name pf and it is for a function pointer that takes two integers as arguments and returns an integer.




回答5:


typedef works as:

Define unknown type with known types.

So it defines function type that takes two int argument and return int.



来源:https://stackoverflow.com/questions/17288678/typedef-int-pf-needs-explaining

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!