Consider the following program:
#include <iostream>
typedef void (*fptr)(...);
void foo(fptr func) {
(*func)(12);
}
void bar(int x) {
std::cout << "bar : " << x << std::endl;
}
int main() {
foo(fptr(bar));
}
This compiles, runs and prints bar : 12
on at least one compiler :) I found this in some legacy code I am supposed to maintain, and I wonder if this is safe/defined?
bar
does not match the type fptr
, so the only way to get this to work is by using an unsafe cast. I guess it depends on how the ellipsis-magic works internally, so is that defined in some way?
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.
What the code is doing is undefined behavior. If its working is just by chance, there are no guarantees that it should work. The only thing that can be safely done with a casted function pointer is cast it back to its original type.
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