Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting integer to function pointer in signal code - why does this work?

Tags:

c++

c

unix

I'm reading a book (Advanced Programming in the UNIX Environment) and I'm going through the section on signals.

When using the signal function:

void (*signal(int signo, void (*func)(int)))(int);

the parameter, func, can be a pointer to a function defined by the user, or it can be SIG_ERR, SIG_DFL, or SIG_IGN.

My question isn't on the UNIX part of this, but I wanted to give background. What I really want to know is, the book states that these constants are defiend as:

#define SIG_ERR (void (*)())-1

and the like for 0, and 1.

Now, I have some decent guesses but to save time - can someone tell me what the heck this is doing and why it works?

Also, is there a... erm... cleaner? way to write this assuming I'm using C++ and interacting with this C API?

like image 866
John Humphreys Avatar asked Dec 07 '11 17:12

John Humphreys


People also ask

Can you cast function pointers?

Yes, it can. This is purpose of casting function pointers, just like usual pointers. We can cast a function pointer to another function pointer type but cannot call a function using casted pointer if the function pointer is not compatible with the function to be called.


1 Answers

It's casting an integer to a function pointer;* the placeholder values are presumably chosen so that they could never collide with the values of real function pointers. The implementation of signal presumably then checks the input argument for these special values.


* The C standard allows this (see 6.3.2.3 p.5), although it says that the results are implementation-defined. Obviously, the authors of the OS are able to control the implementation-defined aspects of this, so everything's ok.
like image 95
Oliver Charlesworth Avatar answered Sep 30 '22 17:09

Oliver Charlesworth