Question

having some trouble passing a function as a parameter of another function...

ERROR: Error 1 error C2664: 'wrapper' : cannot convert parameter 1 from 'int' to 'int (__cdecl *)(int)'

int inc( int n )
{
    return n + 1 ;
}

int dec( int n )
{
    return n - 1 ;
}

int wrapper(   int i, int func(int)   )
{
    return func( i ) ;
}   


int main(){

    int a = 0 ;

    a = wrapper(  3, inc( 3 )  ) ;

    return 0 ;

}
Was it helpful?

Solution

You're passing the result of a function call inc(3) to wrapper, NOT a function pointer as it expects.

a = wrapper(3, &inc) ;

OTHER TIPS

Your call is passing an integer, the return value from calling inc(3), i.e. 4.

That is not a function pointer.

Perhaps you meant:

a = wrapper(3, inc);

This would work, and assign a to the value of calling int with the parameter 3.

The line:

 a = wrapper(  3, inc( 3 )  ) ;

is effectively:

a = wrapper(3, 4);

I think you mean:

a = wrapper(3, inc);

This passes a pointer to the inc() function as the second argument to wrapper().

As it is now, wrapper takes an int and a pointer to a function that takes one int and returns an int. You are trying to pass it an int and an int, because instead of passing the a pointer to the function, you're calling the function and passing the return value (an int). To get your code to work as (I think) you expect, change your call to wrapper to this:

a = wrapper(3, &inc);

i had this error in my program:

error C2664: 'glutSpecialFunc' : cannot convert parameter 1 from 'void (__cdecl *)(void)' to 'void (__cdecl *)(int,int,int)'

because i had wrote the method definition later than main method. when i cut the main method and paste it later than definition of function, the error removed.

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