Definition and use of a C function pointer array

Source: Internet
Author: User
Tags mul

1. Using a function pointer array to implement the calculator

2. Call the corresponding function by a function pointer variable

#include <stdio.h>int Add (int a,int b) {return a+b;} int sub (int a,int b) {return a-A;} int mul (int a,int b) {return a*b;} int div (int a,int b) {return a/b;} void Make_menu () {printf ("****************************\n");p rintf ("Please select menu: \ n");p rintf ("1: plus 2: minus 3: Multiply 4: except 0: Exit \ n");} /* Define the function pointer array variable (INT,INT) corresponding to the function pointer array to the list of functions */int (*fun_array[4]) (int,int) = {Add, sub, mul, Div}; int main () {int i,j;int cmd;while (1) {make_menu (); scanf ("%d", &cmd); if (cmd==0) {break;} if (cmd>=1&&cmd<=4) {printf ("Please enter 2 numbers:"), scanf ("%d%d", &i,&j);//function pointer array to invoke the corresponding function int result = Fun_array[cmd-1] (I,J); equivalent to int result = (*fun_array[cmd-1]) (I,J);//function pointer variable to invoke the corresponding function//int (*p) (int,int) = Fun_array[cmd-1];//int  Result = P (i,j);p rintf ("result:%d\n", result);}} return 0;}

  

Definition and use of a C function pointer array

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.