在对函数指针进行 typedef 时 * 是强制性的吗?

is * mandatory while doing typedef of a function pointer?

我在编写一段 "unintended" 代码时想到了这个问题,并成功编译并获得了所需的行为。后来我注意到更改的奇怪之处,并意识到我使用了完全相反的顺序来执行函数指针的 typedef。现在我很困惑 "unintended" 错误在语法上是否真的正确。

惯例:

typedef void* (*_malloc_fail_handler_ptr)(int) __attribute__ ((unused));
_malloc_fail_handler_ptr _malloc_fail_handler = NULL;

我的"unintended"代码:

typedef void* (_malloc_fail_handler_ptr)(int) __attribute__ ((unused));
_malloc_fail_handler_ptr* _malloc_fail_handler = NULL;

语法正确。对于第二种情况,_malloc_fail_handler_ptr 的类型是函数,而不是函数指针。然后 _malloc_fail_handler_ptr* 的类型是指向函数的指针。所以对于第一种和第二种情况,变量的类型_malloc_fail_handler是一样的。

第二个唯一的问题是命名:

typedef void* (*_malloc_fail_handler_ptr)(int) __attribute__ ((unused)); 

那里,_malloc_fail_handler_ptr 是一个 指向 函数的指针,它接受一个 int 并返回 void*

typedef void* (_malloc_fail_handler_ptr)(int) __attribute__ ((unused)); 

这里,_malloc_fail_handler_ptr 是一个接受 int 并返回 void* 的函数。它是函数类型,而不是指针类型。所以后缀 _ptr 具有误导性。但是就像任何(在 C++ 中,non-reference)类型一样,您总是可以编写 T* 来获取指向 T 的指针,所以这是可行的。


简化一切以避免笨拙的函数语法,你的问题归结为:

typedef int* ptr;
ptr x = NULL;

对比:

typedef int ptr;
ptr* x = NULL;

两者在句法上都很好,但第二个的命名很容易引起误解。