Use a void function as parameter of another

7

Suppose I need a function to run to a certain point, call another, do some action, call another function, do one more action and finish executing. Whereas the called functions are given a parameter but give no return to the first. Ex:

void comeco_fim(/*função 1*/, /*função 2*/){
  printf("começo");

  //executa a função 1

  printf("texto");

  //executa a função 2

  printf("fim");
}

In this case, this function would not repeat the same sequence every time I needed it, considering that the order does not change, only some parts change in the middle. How to do this? Or is there a more correct way?

    
asked by anonymous 22.09.2015 / 18:27

1 answer

7

If I understand what you want, you need to declare the parameter as a pointer to a function. So:

#include <stdio.h>

void comeco_fim(void (*func1)(void), void (*func2)(void)) {
    printf("começo");
    func1(); //está usando a variável para chamar a função
    printf("texto");
    func2();
    printf("fim");
}

void funcao1() {
    printf("funcao1");
}

void funcao2() {
    printf("funcao2");
}
int main(void) {
    comeco_fim(funcao1, funcao2); //está passando as funções definidas acima.
    return 0;
}

See running on ideone .

void (*func1)(void) indicates that the variable func1 will be of type function that receives no parameter and returns nothing. Only a function with this signature can be passed as an argument to this parameter.

    
22.09.2015 / 18:37