Learn point C language (38): function

Source: Internet
Author: User
Tags mul printf

Review the definition of function and the declaration of function first:

//这是一个求和函数的定义:
int add(int x, int y)
{
  return(x + y);
}

//可以这样声明:
int add(int x, int y);

//也可以这样声明:
int add(int, int);

Define a function pointer to declare a function almost, with (*) including the function can:

//像这样:
int (*pfun)(int, int);

//或这样:
int (*pfun)(int x, int y);

//也可以:
typedef int (*pfun)(int, int);

//这就声明了一个叫 pfun 的函数指针, 能被它指向的函数一定要有相同的参数格式.

1. Simple example:

#include <stdio.h>

int add(int x, int y) {return(x + y);}
int sub(int x, int y) {return(x - y);}
int mul(int x, int y) {return(x * y);}
int div(int x, int y) {return(x / y);}

int main(void)
{
  int (*pf)(int, int);

  pf = add;
  printf("%d\n", pf(9, 3)); /* 12 */

  pf = sub;
  printf("%d\n", pf(9, 3)); /* 6 */

  pf = mul;
  printf("%d\n", pf(9, 3)); /* 27 */

  pf = div;
  printf("%d\n", pf(9, 3)); /* 3 */

  getchar();
  return 0;
}

2. Array of function pointers:

#include <stdio.h>

int add(int x, int y) {return(x + y);}
int sub(int x, int y) {return(x - y);}
int mul(int x, int y) {return(x * y);}
int div(int x, int y) {return(x / y);}

int main(void)
{
  int (*pf[4])(int, int) = {add, sub, mul, div};

  printf("%d\n", pf[0](9, 3)); /* 12 */
  printf("%d\n", pf[1](9, 3)); /* 6 */
  printf("%d\n", pf[2](9, 3)); /* 27 */
  printf("%d\n", pf[3](9, 3)); /* 3 */

  getchar();
  return 0;
}

3. Use function pointer to do parameter:

#include <stdio.h>

int add(int x, int y) {return(x + y);}
int sub(int x, int y) {return(x - y);}
int mul(int x, int y) {return(x * y);}
int div(int x, int y) {return(x / y);}

int math(int(*pfun)(int, int), int x, int y) {
  return pfun(x, y);
}

int main(void)
{
  printf("%d\n", math(add, 9, 3)); /* 12 */
  printf("%d\n", math(sub, 9, 3)); /* 6 */
  printf("%d\n", math(mul, 9, 3)); /* 27 */
  printf("%d\n", math(div, 9, 3)); /* 3 */

  getchar();
  return 0;
}

Back to "Learn point C-Directory"

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.