Use a void function as a parameter of another

Asked

Viewed 702 times

7

Let’s assume that I need one function to perform to a certain point, call another, do some action, call another function, do one more action and finish executing. Whereas the called functions receive 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 serve to not repeat the same sequence every time I needed it, considering that the order does not change, only change some parts in the middle. How to do this? Or is there any more correct way?

1 answer

8


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.
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.