技术咨询:两类函数指针与指针函数声明(含extern修饰)的区别
Alright, let's break down these two pairs of C declarations—they look nearly identical but represent completely different constructs, which is a classic gotcha for anyone working with function pointers in C.
第一组:int (*cmp)(void) 与 int *cmp(void)
Parentheses are everything in C declaration syntax, so let's unpack the core difference here:
int (*cmp)(void)
This declares a pointer to a function that takes no arguments and returns an int.
- The parentheses wrapping
(*cmp)are critical—they force the compiler to interpretcmpas a pointer first, before parsing the function syntax attached to it. - In simple terms:
cmpis a pointer, and it points to a function that takes nothing and spits back an integer. - Example usage:
int my_func(void) { return 42; } int (*cmp)(void) = &my_func; // Assign the function's address to cmp printf("%d\n", (*cmp)()); // Calls my_func, outputs 42 (you can also write cmp() directly!)
int *cmp(void)
This declares a function that takes no arguments and returns a pointer to an int.
- Here, no parentheses wrap
*cmp, so the function syntax (cmp(void)) takes priority. The*only applies to the function's return type. - Plain language:
cmpis a function name—call it, and it hands you back a pointer to an integer value. - Example usage:
int *cmp(void) { static int value = 100; return &value; // Return pointer to the static integer } int *ptr = cmp(); printf("%d\n", *ptr); // Outputs 100
第二组:extern int (*func)(void); 与 extern int *func(void);
The extern keyword only changes one thing: it tells the compiler that the identifier (func) is defined in another source file or translation unit. The underlying type of each declaration is exactly the same as the first group.
extern int (*func)(void);→ Declares that somewhere else in your codebase, there's a function pointerfunc(pointing to a void-arg, int-return function) already defined.extern int *func(void);→ Declares that somewhere else, there's a functionfunc(taking no args, returning an int pointer) already defined.
extern just lets you reference something existing elsewhere without redefining it in the current file.
内容的提问来源于stack exchange,提问作者gnued

