C Language Learning 019: function pointer, language learning 019

Source: Internet
Author: User

C Language Learning 019: function pointer, language learning 019

In C language, the function name is also a pointer variable. For example, when you create an add (int n, int m) function, you also create a pointer variable named add, therefore, we can assign a value to a function pointer as a type and pass it as a parameter.

Formula for creating function pointers in C language:

Return type (* pointer variable) (parameter type)

1 # include <stdio. h> 2 3 int add (int n, int m) {4 return n + m; 5} 6 7 int sub (int n, int m) {8 return n-m; 9} 10 11 int main () {12 int n = 10; 13 int m = 5; 14 int (* calculate) (int, int ); // create a variable named calculate 15 calculate = add; 16 int result = calculate (n, m); // equivalent to add (n, m ); 17 printf ("% I \ n", result); 18 calculate = sub; 19 result = calculate (n, m); // sub (n, m ); 20 printf ("% I \ n", result); 21 return 0; 22}

Although the function pointer is a pointer, when using it, we can omit the "*" statement, such as the calculate (n, m) above. We do not need to write (* calculate) (n, m); it should be noted that the function pointer only accepts the function address that is the same as its return value and parameter.

Function pointer Array
1 # include <stdio. h> 2 3 enum response_type {DUMP, SECOND_CHANCE, MARRIAGE}; 4 typedef struct {5 char * name; 6 enum response_type; 7} response; 8 9 void dump (response r) {10 printf ("dump % s \ n", r. name); 11} 12 13 void second_chance (response r) {14 printf ("second_chance % s \ n", r. name); 15} 16 17 void marriage (response r) {18 printf ("marriage % s \ n", r. name); 19} 20 21 int main () {22 response r [] = {"Mike", DUMP}, {"Luis", SECOND_CHANCE}, {"Matt ", SECOND_CHANCE },{ "William", MARRIAGE }}; 23 void (* replies []) (response) = {dump, second_chance, marriage }; // create a function pointer array 24 int I; 25 for (I = 0; I <4; I ++) {26 replies [r [I]. type] (r [I]); 27} 28 return 0; 29}

 

Related Article

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.