1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>


void say_hi() {
    printf("Hi\n");
}


void say_bye() {
    printf("Bye\n");
}


void say_something(void(*say_fn)()) {
//                 ▼       ▼     └───> types of parameters that say_fn takes
//  «type fn returns»  «name of parameter»
    say_fn();
}


int main(int argc, char* argv[]) {

    // Declare a variable called 'fn_to_say_something'.
    // ∙ The type of 'fn_to_say_something' is "address of a function returning
    //   void and taking no parameters."
    // ∙ Initialize 'fn_to_say_something' to the address of function say_hi(…).
    void (*fn_to_say_something)() = say_hi;

    // Call say_something(…), passing fn_to_say_something, which is currently set to the
    // address of say_hi(…).
    say_something( fn_to_say_something );

    // Set fn_to_say_something to the address of say_bye(…).
    fn_to_say_something = say_bye; // fn_to_say_something is now address of say_bye(…).

    // Call say_something(…), passing fn_to_say_something, which is now set to the
    // address of say_bye(…).
    say_something( fn_to_say_something );  
    
    return EXIT_SUCCESS;
}
/* vim: set tabstop=4 shiftwidth=4 fileencoding=utf-8 noexpandtab: */

© Copyright 2023 Alexander J. Quinn         This content is protected and may not be shared, uploaded, or distributed.