signal函数两种等效声明的技术确认与解析
signal() Declarations Equivalent? Short answer: Yes, these two declarations are completely equivalent — they describe the exact same function signature for signal(). Let’s break down why, step by step.
First, Let’s Understand the Typedef
The line:
typedef void (*sighandler_t)(int);
creates a type alias sighandler_t for a specific function pointer type: a pointer to a function that takes an int parameter and returns void. This shorthand exists to simplify the messy syntax of function pointer declarations, making code easier to read.
Declaration 1: The Simplified Version
Using the typedef, the signal function is declared as:
extern sighandler_t signal(int signum, sighandler_t handler);
Let’s parse this clearly:
signalis a function that accepts two arguments:- An
int(signum, the signal number to handle) - A
sighandler_t(handler, the function to run when the signal is triggered)
- An
- The function returns a
sighandler_t— this is the previously registered signal handler, so you can restore it later if needed.
Declaration 2: The "Raw" Function Pointer Syntax
The second declaration skips the typedef and uses the full, unaliased function pointer syntax:
extern void (*signal(int sig, void (*func) (int)))(int);
This looks daunting at first, but let’s unwrap it from the inside out:
- Start with the function name:
signalis a function. - Its parameters:
(int sig, void (*func)(int))— it takes anintand a function pointer (func) that accepts anintand returnsvoid. - The return type: the entire declaration is wrapped in
void (* ... )(int), which meanssignalreturns a pointer to a function that takes anintand returnsvoid.
If you replace every instance of void (*)(int) with our typedef sighandler_t, you end up exactly with Declaration 1. That’s the core reason they’re identical.
Why Two Forms?
The second form is common in older C code or contexts where a typedef isn’t used (or isn’t available). The typedef version is just a cleaner, more readable way to express the same signature — it hides the verbose function pointer syntax, making the code’s intent clearer at a glance.
内容的提问来源于stack exchange,提问作者Soner from The Ottoman Empire

