Broad Network


Callback Function in the C Computer Language

Part 31 of the Complete C Course

Foreword: Callback Function in the C Computer Language

By: Chrysanthus Date Published: 22 Jun 2024

Introduction

Remember that when dealing with function, there is the called function and there is the function call. The called function is the function definition. The function call, calls the function definition. In a callback function scheme, there are two functions: the principal function definition (with its call) and the actual callback function definition (with its own call). The callback function is defined (in theory) in the principal function call. In the body of the principal function, certain values become arguments to the callback function. The principal function must have at least one argument, which is the definition of the callback function (in theory). The callback function can have zero or more arguments. The following program illustrates the scheme:

    #include <stdio.h>
    
    void cbFn(char stri[], char cha) {
        printf("%s", stri);
        printf("%c\n", cha);        
    }
    
    void princFn (int no, void (*func)(char stri[], char cha)) {
            char str[] = "We are learning ";
            char ch = 'C';
            
            (*func)(str, ch);
        }

    int main(int argc, char *argv[])
    {
        princFn(10, cbFn);    //principal function call

        return 0;
    }

In C, in practice, the coded definition of the callback function, is separated from the principal function. In the above program, after the inclusion of the stdio library header, "stdio.h" the callback function is defined. After the definition of the callback function, is the definition of the principal function. In the definition of the principal function, the second parameter in its signature, is the signature of a pointer to a function. This pointer to a function has the same parameters and return type as the callback function. The last statement in this principal function definition, is a function call by pointer, with arguments, corresponding to this second parameter, with same function name.

In the C main() function, the call to the principal function is:

        princFn(10, cbFn);

The second argument here, is the callback function name without parentheses and arguments. The arguments were sent within the definition of the principal function. The output of the program is:

    We are learning C




Related Links

More Related Links

Cousins

BACK NEXT

Comments