So I’m practicing pointers to functions, and tried out making this simple program, here’s a snippet of it. It still gives me an error “invalid lvalue” when it comes to assigning the address. funcptr = &addnum for example. Also I can’t help but wonder what’s the use of this? Isn’t it much simpler to call the function? Or am I misunderstanding something
#include <stdio.h>
int arithnum(int base);
int addnum(int base,int new);
int subnum(int base,int new);
int mulnum(int base,int new);
int divnum(int base,int new);
typedef int *ptrdef(int,int);
int arithnum(int base)
{
char operator;
int operand;
ptrdef funcptr;
printf("Enter operator: ");
scanf("\n%c",&operator);
printf("Enter second operand: ");
scanf("%d",&operand);
switch(operator)
{
case '+':
funcptr = &addnum;
break;
case '-':
funcptr = &subnum;
break;
case '*':
funcptr = &mulnum;
break;
case '/':
funcptr = &divnum;
break;
}
return funcptr(base,operand);
}
ITYM
as your version is a function which returns an
int *while you want a function pointer which returns anint.Just a hint: I know that the following is not common sense, but I prefer to
typedefthe function itself and then doin order to get bitten by an error instead of a warning if I accidentally change the declaration of
therealfunction.