Peter Nilsson <ai***@acay.com.auwrites:
Ben Bacarisse <ben.use...@bsb.me.ukwrote:
>viza <tom.v...@gm-il.com.obviouschange.invalidwrites:
Can one reliably call a function via a function
pointer of different type
Yes.
as below?
No! Â*You can do it but not like this.
struct some_struct {
Â* int some_int;
};
int some_function( struct some_struct *struct_ptr ){
Â* return struct_ptr-some_int;
}
int main( void ){
Â* struct some_struct a_struct= { 42 };
Â* int (*function_pointer)(void*)= & some_function;
This initialisation requires a diagnostic but it is
perfectly OK if you supply a cast (and I prefer to
have no & operator):
int (*function_pointer)(void*)= (int (*)(void *))some_function;
Â* return (*function_pointer)( & a_struct );
Since some_function is not variadic, better is...
int (*function_pointer)() = some_function;
Yes, that's neater (and I had forgotten you could still do this in
"modern" C).
I was also pleasantly surprised to find that the compiler is obliged
to diagnose the situation where the default argument promotions could
result in a problem at call time; since in such cases the types are no
longer compatible. This is (I flatter myself) a subtle point that had
passed me by.
This means that it is not just that some_function is not variadic that
makes the initialisation valid. As you mentioned in another post, it
is the fact that the declared arguments to some_function are not
altered by the default argument promotions.
For those as slow on the uptake as myself, I believe that if
some_function is declared:
int some_function(float);
the compiler must diagnose a constraint violation, but if it were
declared
int some_function(double);
the initialisation is from a compatible type. This makes your form
more type-safe (within the limits that C permits) than my version with
the explicit casts. There is no way that C can properly type-check
the final call (given that we have now lost the original function
type) but at least it can check for a subtle incompatibility that
could otherwise slip by.
Thank you for pointing this out.
<snip>
--
Ben.