Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top