Re:Higher-order programming in C
by forgotusername on Saturday June 30, 2012 @07:09AM
(#4181350)
The ability to cast a function pointer to a regular pointer is an implementation behavior (supported on every machine you'd want to use, but nonetheless it's not standard C)
[ Parent
| on HN ]
That's undefined behavior meaning that anything might happen, including appearing to work [most of the time]. C allows casts between two data pointers and between two function pointers, but not cast that cross the data/function boundary.
Any cast that crosses function/data boundary must go through suitably large integer type; UB results if you cast a pointer to a too-small integer type. See my other comment in this thread for a reference to the standard.
That's interesting to know. Is there no general data type that's guaranteed to hold a function pointer?
Only function pointer types. An indirect function call on some architecture, for example, could require that when one makes an indirect call one sets up several registers in addition to jumping to a particular location in memory, and none of the registers that need to be set up can be derived from the jump target. So in practice your function pointers would need to actually be structures containing those register values and the jump target. Or you might need to pass around a tuple of target and calling convention, although the C standard limits the ways you could implement that (namely by requiring that function pointers cast to and from other function pointer types will compare as equal, and will still work when they are cast to the correct type.)
Re:Higher-order programming in C
by Daniel_Newby on Saturday June 30, 2012 @11:15AM
(#4181817)
There are quite a few Harvard architecture microcontrollers and DSPs for which this is not true. (At least for some values of "want to use" ;-).
Re:Higher-order programming in C
by forgotusername on Saturday June 30, 2012 @12:26PM
(#4182008)
I've never written code for these architectures, but my assumption was that a modern GCC will happily bodge this for you in software, so its probably only super ancient/exotic stuff for which the lack of ability to cast applies
Re:Higher-order programming in C
by Daniel_Newby on Saturday June 30, 2012 @12:35PM
(#4182035)
Yeah, the compiler will probably force it to work.
On the other hand, some of the the popular PIC microcontrollers have an instruction pointer that is wider than the data registers. Good luck doing functional programming on that!