cparametersscopefunction-pointersfunction-prototypes

Passing a function pointer with it's own parameters in C


#include <stdio.h>

void runner(void (* function)(int in)){
  (*function)(in); 
}

void print(int in){
 printf("%d\n", in);
}

int main(){
 // 
 return 0;
}

Above code is not compiling and shows this error: 'in' undeclared.

Do I have to pass the parameters of a function pointer separately like this?

void runner(void (* function)(int), int in){
  (*function)(in); 
}

i.e form a syntax point of view, there is no way to pass the function pointer and its argument all at once?


Solution

  • Parameters are not passed. It is arguments that are passed.

    So this function declaration

    void runner(void (* function)(int in)){
      (*function)(in); 
    }
    

    has only one parameter: a pointer to a function, But if you want to call the pointed function that expects an argument then you need to supply an argument.

    In this declaration of a function pointer

    void (* function)(int in)
    

    the function parameter in has the function prototype scope..

    You may declare the function parameter without its identifier like

    void (* function)(int)
    

    So you have to declare the function with two parameters like

    void runner(void (* function)(int), int in ){
      function(in); 
    }
    

    Pay attention to that to dereference the pointer to function is redundant.

    All these calls as for example

    ( *function )( int );
    

    or

    ( *****function )( in );
    

    are equivalent to

    function( in );