Home>Article> How to implement callback function in C language

How to implement callback function in C language

Lisa Kudrow
Lisa Kudrow Original
2019-04-16 14:12:26 6274browse

The callback function is to implement different functions through a unified interface. The callback function in C language is to call different callback functions in the code according to the different parameters passed

The callback function is a program A function that cannot be called explicitly by members; the callback function is called by passing the address of the callback function to the caller. The use of callback functions is necessary. When we want to implement different content through a unified interface, callback functions are very suitable.

How to implement callback function in C language

【Recommended tutorial:C language tutorial

For example, we wrote different display functions for several different devices:

void TVshow(); void ComputerShow(); void NoteBookShow()...等等。

This is because we want to use a unified display function, and we can use the lost function at this time.

void show(void (*ptr)());

When used, different callback functions are called according to the parameters passed in.

Different programming languages may have different syntax. Here is an example of a callback function in C language. One callback function does not take parameters, and the other callback function takes parameters.

#include  #include  int Test1() { int i; for(i=0; i<30; i++) { printf("The %d th charactor is: %c\n", i, (char)('a' + i%26)); } return 0; } int Test2(int num) { int i; for (i=0; i
      

The rendering is as follows

How to implement callback function in C language

The above call is implemented by passing the address of the callback function to the caller, but it should be noted that the callback function with parameters usage.

To implement callbacks, you must first define a function pointer. The definition of function pointers is briefly mentioned here.

For example:

int (*ptr)();

Here ptr is a function pointer, in which the brackets of (*ptr) cannot be omitted,

because the priority of brackets is higher than that of asterisks, so It becomes a function declaration with an integer return type.

Summary: The above is the entire content of this article, I hope it will be helpful to everyone.

The above is the detailed content of How to implement callback function in C language. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn