Casting pointer-to-function with ellipsis
Asked Answered
L

1

8

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?

Logomachy answered 18/10, 2011 at 13:50 Comment(3)
It works on my compiler with ints too, but if (just for fun) you wish to proove to yourself how evil it is, convert the program to run with floats... this doesn't work on my compiler.Liederman
I don't think you can even have a legal function that matches the signature of fptr, since variadic functions always need at least one named argument. So you can define the type and make a pointer variable, but you can't assign it any valid value.Myrmeco
@Kerrek: I just now discovered that too. It is legal to define such a function in C++ (in C it isn't), but as you say, there is no way to actually access the arguments.Sherlynsherm
W
10

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.

Wattmeter answered 18/10, 2011 at 13:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.