c function as parameter code example
Example 1: call a function inside argument of another function c
int main (void) {
Repeat(SayHello,4);
Repeat(SayGoodbye,2);
}
void Repeat(void (*fct)(int), int i) {
for (int j=0, j<i; j++) {
(*fct)(j);
}
}
void SayHello(int nbr) {
printf("Hello n.%d\n", nbr);
}
void SayGoodbye(int nbr) {
printf("Goodbye n.%d\n", nbr);
}
Result :
Hello n.0
Hello n.1
Hello n.2
Hello n.3
Goodbye n.0
Goodbye n.1
Example 2: passing a function as an argument in c
void func ( void (*f)(int) ) {
for ( int ctr = 0 ; ctr < 5 ; ctr++ ) {
(*f)(ctr);
}
}
Example 3: passing a function as an argument in c
void func ( void (*f)(int) );