Possible Duplicate:
what's the meaning of this piece of code? void (*signal(int sig, void (*func)(int)))(int);
I have a complex declaration which have been taken from the "signal.h" header file, and below is the declaration.
void (*signal(int sig, void (*func)(int)))(int);
Now, how do I parse it? As
signal is function taking two arguments ‘sig’ of int type and ‘func’, which is a pointer to a function taking int as an argument and returns void type; it returns a pointer to the function taking int as argument and returning void.
Is it OK or signal is a pointer to function?
This is a simple rule that allows you to interpret any declaration. It runs as follows: Start reading the declaration from the innermost parentheses, go right, and then go left.
Function pointers can be useful when you want to create callback mechanism, and need to pass address of a function to another function. They can also be useful when you want to store an array of functions, to call dynamically for example.
Start with the leftmost identifier and work your way out, remembering that []
and ()
bind before *
, so *a[]
is an array of pointers, (*a)[]
is a pointer to an array, *f()
is a function returning a pointer, and (*f)()
is a pointer to a function:
signal -- signal
signal( ) -- is a function
signal( sig, ) -- with a parameter named sig
signal(int sig, ) -- of type int
signal(int sig, func ) -- and a parameter named func
signal(int sig, (*func) ) -- which is a pointer
signal(int sig, (*func)( )) -- to a function
signal(int sig, (*func)(int)) -- taking an int parameter
signal(int sig, void (*func)(int)) -- and returning void
*signal(int sig, void (*func)(int)) -- returning a pointer
(*signal(int sig, void (*func)(int)))( ) -- to a function
(*signal(int sig, void (*func)(int)))(int) -- taking an int parameter
void (*signal(int sig, void (*func)(int)))(int); -- and returning void
signal
associates a signal handler function func
with a signal sig
, and returns the pointer to the old signal handler function:
void new_interrupt_handler(int sig)
{
... // do something interesting with interrupt signal
}
int main(void)
{
void (*old_interrupt_handler)(int);
...
/**
* Set up our new interrupt handler
*/
old_interrupt_handler = signal(SIGINT, new_interrupt_handler);
...
/**
* Restore original interrupt handler
*/
signal(SIGINT, old_interrupt_handler);
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With