hyderabadblues said:
I have problem.I want to create function pointer with typedef so that
I can use it for both functions which takes one integer parameter and
function which take none because of some obvious reasons of code
merging from two different projects.
type void (*FP)(int i=0);
But above piece of code gives me a error, that I cannot have default
parameters.How can I change my code
You can't have default parameters for functions - you would need C++
for that. Moreover, having a default argument won't help you also in
C++ if the function to be called doesn't take arguments - you would
only be able to call functions that take single int arguments but
you could leave out that argument when calling the functions (if I
remember that bit about C++ correctly - better ask in comp.lang.c++).
Concerning how to create a type that can store function pointers to
functions returning the same type but with differing arguments here
is a trivial example where it is used that a empty set of arguments
means that the number (and types) of the arguments is unspecified:
#include <stdio.h>
typedef void( * FP )( );
void foo( int x )
{
printf( "%d\n", x );
}
void bar( void )
{
printf( "nothing\n" );
}
int main( void )
{
FP fp = foo;
fp( 2 );
fp = far;
fp( );
return 0;
}
Of course, this will not allow the compiler to check if there are as
many arguments (and if they are of the correct types) as the function
you call needs. That's the price you have to pay. An alternative might
be using a union to tell the compiler explicitely which type the func-
tion has:
#include <stdio.h>
typedef union {
void( * one_int_arg )( int );
void( * no_args )( void );
} FP;
void foo( int x )
{
printf( "%d\n", x );
}
void bar( void )
{
printf( "nothing\n" );
}
int main( void )
{
FP fp[ 2 ];
fp.one_int_arg = foo;
fp.one_int_arg( 2 );
fp.no_args = bar;
fp.no_args( );
return 0;
}
Regards, Jens