3 ms·
The potential trouble is if the function pointer goes through a void* wormhole. (All of these types will be lost... like...) In C you can cast a pointer, okay
by Gibbon1 11y ago
The potential trouble is if the function pointer goes through a void* wormhole. (All of these types will be lost... like...)
In C you can cast a pointer, okay anything really, to a function pointer and then call it.
int foo(int a, int b){return a+b; }
void *vptr = foo;
int (*yolo)(int a) = vptr;
int c = yolo(10); // Cthulhu come
This sort of thing can happen when you pass a function pointer into some sort of callback mechanism+. When you get it back you have to cast it to the right type and then call it. So there is a disconnect between the cast and the function definition, unless you tie both together with a typedef.
+ Often helpful for an api that takes a callback to also record, who the caller was and some arbitrary bit of data. The arbitary bit of data might be a function pointer.
- jcranmer 11y agoActually, casting between void * and void (*)() is not legal C. You can convert between pointers of different object types, and you can convert between pointers of different function types, but you're not allowed to convert between a pointer of object type and pointer of function type (c.f. N1570, §J.5.4 (which makes it explicit) and §6.3.2.3 (where it's implicit by omission)). This is however a very common extension allowed in most compilers, since most processors that people encounter keep code and data in the same memory address pool. But on DSPs, it's common for data and code memory to be distinct address spaces, and the two pointer types aren't necessarily the same size.