Function pointer usage

Source: Internet
Author: User

Pointers can be used not only to point to basic types of data, but also to functions. If we have a function pointer, we can pass it as a parameter to other functions. One of its applications is the callback function. The Declaration Prototype of the function pointer (Declaration Prototype) typename (* pointer_name) (parameters ...) since the pointer points to a specific function, assume there is a simple addition function: [cpp] int add (int a, int B) {return a + B ;} this function is simple. It accepts two Integer Parameters and returns the sum of the two integers. The following statement declares a function pointer: [cpp] int (* foo) (int, int). In short, this statement is similar to the function declaration, however, an asterisk (*) must be added before the function name and parentheses must be added. In addition, it should be noted that the returned type declared by the function pointer, the number of parameters, and the parameter type must correspond one to one. The function pointer name must be a valid identifier, and foo is used here. The following initialization function pointer: [cpp] foo = add; // or foo = & add; Use the pointer function: [cpp] // normal function call printf ("% d \ n", add (); // call printf ("% d \ n ", foo (1, 2); // or printf ("% d \ n", (* foo) (1, 2); pass the function pointer variable as a parameter to another function. [Cpp] # include <stdio. h> void pay () {printf ("paying 1 $ \ n");} void got (void (* func_p_para) (), char * goods) {func_p_para (); // call printf ("buy % s", goods);} int main () {void (* foo) (); foo = pay; got (foo, "1 T Memmory");} Over...

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.