简体   繁体   中英

Why typedef for a function pointer is different from a regular typedef?

typedef regularly works like: typedef <type> <type_alias> . But typedefs for function pointers seems to have different structure: typedef int (*fn)(char *, char *); - there is no type alias, just a single function signature.

Here is the example code:

#include <stdio.h>

typedef void (*callback)(int);

void range(int start, int stop, callback cb) {
    int i;
    for (i = start; i < stop; i++) {
        (*cb)(i);
    }
}

void printer(int i) {
    printf("%d\n", i);
}

main(int argc, int *argv[])
{
    if (argc < 3) {
        printf("Provide 2 arguments - start and stop!");
    }

    range(atoi(argv[1]), atoi(argv[2]), printer);
}

So - why typedef s for function pointers are different?

The syntax for using typedef to define a function pointer type follows the same syntax as you would use for defining function pointers.

int (*fn)(char *, char *);

Defines fn to be a pointer to a function ...

typedef int (*fn)(char *, char *);

Defines fn to be a type that is a pointer to a function ...

It works the same. You just have to look at it in a slightly different way. typedef defines your own type name by putting it in exactly the place where the identifier of your variable would go without the typedef . So

uint8_t foo;

becomes

typedef uint8_t footype;
footype foo;

edit : so "R Sahu" was a bit faster and see his example for the same principle applied to function pointers.

C declaration syntax is much more complicated than type identifier , with examples like

T (*ap)[N];             // ap is a pointer to an N-element array
T *(*f())();            // f is a function returning a pointer to
                        // a function returning a pointer to T

Syntactically, typedef is treated as a storage class specifier like static or extern . So you can add typedef to each of the above, giving

typedef T (*ap)[N];     // ap is an alias for type "pointer to N-element array
typedef T *(*f())();    // f is an alias for type "function returning
                        // pointer to function returning pointer to T"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM