How to pass a function as parameter in C?

14

I wanted to know how the function passed by parameter works just like in pthread_create (thread,atributo,rotina,argumento); . In the rotina field a function is placed in void* .

    
asked by anonymous 30.01.2014 / 02:01

1 answer

23

In C and C ++, in addition to normal pointers it is possible to create pointers to functions. Just as a normal pointer points to a memory region from where you can read or write a value, a pointer to function points to a function, which can be called as a normal function.

//func é uma funão normal
void func(int x) { ... }

//func_ptr é um ponteiro para função void que aceita um int de parâmetro 
void (*func_ptr)(int); 

//func_ptr passa a apontar para func
func_ptr = &func;

//chama func, através do ponteiro
func_ptr(42);

Using & before the function name is optional, usually only the name itself is used.

The syntax for declaring function pointers is not very complicated. Basically it is:

<tipo-de-retorno> ( *<nome-da-variável> ) ( <parâmetros> )

The parentheses are important to indicate that * is bound to the variable. Without them would be declared a normal function that returns a pointer.

// ponteiro de função que aceita char* e retorna int 
int (*fun_ptr)(char *); 

// função que aceita char* e retorna int* 
int *fun_ptr(char *); 

For ease of use, you can use typedefs

// FuncPtr é um ponteiro para funções que recebem e retornam char*
typedef char *(*FuncPtr)(char *);

// Cria um ponteiro de função e atribui a função gets a ele
FunPtr ptr = gets;

In addition to variables as in the example, you can declare function parameters, as in the case quoted in the question. Thus it is possible to customize algorithms by passing variable parts of them as function.

#include <stdio.h>

int soma(int a, int b) { return a + b; }
int multiplica(int a, int b) { return a * b; }

typedef int (*Operacao)(int,int);

//Executa uma operação binária sobre dois operandos
int opera(int a, int b, Operacao op) {
  return op(a,b);
}

int main() {
  printf("%d\n", opera(3, 4, soma));       //imprime 7
  printf("%d\n", opera(3, 4, multiplica)); //imprime 12
}
    
30.01.2014 / 02:22