3

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 ;

}

5 Answers 5

5

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

a = wrapper(3, &inc) ;

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

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().

Comments

1

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);

1 Comment

many thanks for the quick replies everyone ..I had this problem once before and somehow managed to get it working without understanding the issue ...now this time it works and I understand why ..thanks again
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.