Function Types in C (and C++)

Paul J. Lucas - Dec 8 '21 - - Dev Community

Even after programming in C for decades, I occasionally still discover things about it. While typedefs of pointer to function are common, I just discovered that you can have typedefs of function by stumbling across their use in some open-source project (though I don't recall which one). That is instead of the common:

typedef void (*PF)(int);
PF pf;                    // pf is a pointer to function
Enter fullscreen mode Exit fullscreen mode

you can instead do:

typedef void F(int);
F *pf;                   // pf is (also) a pointer to function
Enter fullscreen mode Exit fullscreen mode

One advantage the latter is that it makes it more obvious that you're dealing with pointers.

I suppose the reason for not knowing about typedefs of function is that there are no such examples in either the first or second editions of The C Programming Language (though there are examples of typedefs of pointer to function). There is, however, an example in the C99 standard §6.7.7.4:

After

    typedef int MILES, KLICKSP();

the constructions

    extern KLICKSP *metricp;

are all valid declarations. The type of ... metricp is ‘‘pointer to function with no parameter specification returning int’’ ....

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .