Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting pointer-to-function with ellipsis

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?

like image 425
Björn Pollex Avatar asked Oct 18 '11 13:10

Björn Pollex


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

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.

like image 126
K-ballo Avatar answered Sep 20 '22 03:09

K-ballo