C Return Pointer

[Solved] C Return Pointer | C - Code Explorer | yomemimo.com
Question : Function returning function pointer in c

Answered by : muhammad-rizwan-x55rg0nrkwtr

/* Function returning function pointer in c */
#include<stdio.h>
// function declaration
int add(int, int);
int sub(int, int);
int mul(int, int);
int div(int, int);
int mod(int, int);
/* this is a function called function factory which receives parameter
char-type `op` and returns a pointer to another function which receives
two ints and it returns another int */
int (*calc(char op)) (int a, int b);
/* this is also valid and better way
typedef int (*mathPtr)(int, int);
mathPtr calc(char); */
int main( ) { printf(" 10 + 5 = %d\n", calc('+')(10,5)); printf(" 10 - 5 = %d\n", calc('-')(10,5)); printf(" 10 * 5 = %d\n", calc('*')(10,5)); printf(" 10 / 5 = %d\n", calc('/')(10,5)); printf(" 10 %% 5 = %d ", calc('%')(10,5)); return 0;
}
// function definition
int add(int a, int b) { return a+b; }
int sub(int a, int b) { return a-b; }
int mul(int a, int b) { return a*b; }
int div(int a, int b) { return a/b; }
int mod(int a, int b) { return a%b; }
/* return function pointer to int */
/* function def in case of typedef
mathPtr calc(char op) */
int ( *calc(char op)) (int a, int b) { switch (op) { case '+': return add; // or // case '+': return &add; case '-': return sub; case '*': return mul; case '/': return div; case '%': return mod; default: NULL; }
}

Source : https://riptutorial.com/c/example/896/returning-function-pointers-from-a-function | Last Update : Thu, 27 Oct 22

Answers related to c return pointer

Code Explorer Popular Question For C