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 ;

}
tuk
  • 367
  • 1
  • 4
  • 10

5 Answers5

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

Mark B
  • 95,107
  • 10
  • 109
  • 188
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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
alie
  • 11
  • 1
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.

unwind
  • 391,730
  • 64
  • 469
  • 606
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);
Seth Carnegie
  • 73,875
  • 22
  • 181
  • 249
  • 1
    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 – tuk Jun 13 '11 at 15:20
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().

janm
  • 17,976
  • 1
  • 43
  • 61