In: Computer Science
When a function can take another function as a parameter, how can type-checking occur?
(Programming languages)
You cannot pass function to another function as parameter. But, you can pass function reference to another function using function pointers. Using function pointer you can store reference of a function and can pass it to another function as normal pointer variable.
When you pass as a pointer that you need to declare the type of function in parameter itself.
#include <stdio.h> /* Function declarations */ void greetMorning(); void greeEvening(); void greetNight(); void greet(void (*greeter)()); int main() { // Pass pointer to greetMorning function greet(greetMorning); // Pass pointer to greetEvening function greet(greeEvening); // Pass pointer to greetNight function greet(greetNight); return 0; } /** * Function to print greeting message. * * @greeter Function pointer that can point to functions * with no return type and no parameters. */ void greet(void (*greeter)()) { // Call greeter function pointer greeter(); } void greetMorning() { printf("Good, morning!\n"); } void greeEvening() { printf("Good, evening!\n"); } void greetNight() { printf("Good, night!\n"); }
Output