为什么函数指针的 typedef 不同于常规的 typedef?
Why typedef for a function pointer is different from a regular typedef?
typedef
的正常工作方式如下:typedef <type> <type_alias>
。但是函数指针的 typedef 似乎有不同的结构:typedef int (*fn)(char *, char *);
- 没有类型别名,只有一个函数签名。
示例代码如下:
#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);
}
那么 - 为什么函数指针的 typedef
不同?
使用 typedef
定义函数指针类型的语法遵循与定义函数指针相同的语法。
int (*fn)(char *, char *);
将 fn
定义为指向函数的指针 ...
typedef int (*fn)(char *, char *);
将 fn
定义为指向函数的指针类型 ...
效果一样。您只需要以稍微不同的方式来看待它。 typedef
定义您自己的类型名称,方法是将其准确放置在您的变量标识符在没有 typedef
的情况下所在的位置。所以
uint8_t foo;
变成
typedef uint8_t footype;
footype foo;
edit:所以 "R Sahu" 有点快,请参阅他的示例以了解适用于函数指针的相同原理。
C 声明语法比 type identifier
复杂得多,例如
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
在语法上,typedef
被视为存储 class 说明符,如 static
或 extern
。所以你可以将 typedef
添加到上面的每一个中,给出
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"
typedef
的正常工作方式如下:typedef <type> <type_alias>
。但是函数指针的 typedef 似乎有不同的结构:typedef int (*fn)(char *, char *);
- 没有类型别名,只有一个函数签名。
示例代码如下:
#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);
}
那么 - 为什么函数指针的 typedef
不同?
使用 typedef
定义函数指针类型的语法遵循与定义函数指针相同的语法。
int (*fn)(char *, char *);
将 fn
定义为指向函数的指针 ...
typedef int (*fn)(char *, char *);
将 fn
定义为指向函数的指针类型 ...
效果一样。您只需要以稍微不同的方式来看待它。 typedef
定义您自己的类型名称,方法是将其准确放置在您的变量标识符在没有 typedef
的情况下所在的位置。所以
uint8_t foo;
变成
typedef uint8_t footype;
footype foo;
edit:所以 "R Sahu" 有点快,请参阅他的示例以了解适用于函数指针的相同原理。
C 声明语法比 type identifier
复杂得多,例如
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
在语法上,typedef
被视为存储 class 说明符,如 static
或 extern
。所以你可以将 typedef
添加到上面的每一个中,给出
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"