Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typedef int (*pf) needs explaining

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);
like image 403
phoenix Avatar asked Jun 25 '13 03:06

phoenix


2 Answers

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;
}
like image 185
Yu Hao Avatar answered Oct 07 '22 18:10

Yu Hao


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.

like image 5
AnT Avatar answered Oct 07 '22 18:10

AnT