Home > Article > Backend Development > How to find the maximum and minimum values using pointers in C language
Problem description: How to find the maximum and minimum value using C language pointers
The following is a simple one example, used to illustrate pointer variables pointing to functions. Define two functions max and min to find the maximum and minimum values respectively. In the main function, the pointer variable points to the max function or the min function according to whether the number entered by the user is 1 or 2.
codes:#include <stdio.h>int main(){ int max(int,int);//求最大值函数声明 int min(int,int);//求最小值函数声明 int (*p)(int,int);//定义指向函数的指针变量 int a,b,c,n; printf("please input two numbers:");//输入两个数 scanf("%d%d",&a,&b); printf("please choose 1 or 2:");//输入1 or 2 scanf("%d",&n); if(n == 1){ //如果输入1则使 p 指向max函数 p = max; } else if(n == 2){ //如果输入2,使p指向min函数 p = min; } c = (*p)(a,b); printf("a = %d, b = %d\n",a,b); if(n == 1){ printf("max = %d\n",c); } else{ printf("min = %d\n",c); } return 0;}int max(int x, int y) //求最大值函数 { return x > y ? x : y;} int min(int x, int y) //求最小值函数 { return x < y ? x : y;}
Recommended tutorial: "c Language Tutorial"
The above is the detailed content of How to find the maximum and minimum values using pointers in C language. For more information, please follow other related articles on the PHP Chinese website!