tuk
tuk

Reputation: 385

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

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 ;

}

Upvotes: 3

Views: 13952

Answers (5)

alie
alie

Reputation: 11

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.

Upvotes: 1

Seth Carnegie
Seth Carnegie

Reputation: 75150

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

Upvotes: 1

janm
janm

Reputation: 18359

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

Upvotes: 1

Mark B
Mark B

Reputation: 96311

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

a = wrapper(3, &inc) ;

Upvotes: 5

unwind
unwind

Reputation: 400129

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.

Upvotes: 1

Related Questions