Search code examples
cpointersfunction-pointerslvalue

Invalid Lvalue, pointer to function also, whats the use of this? Its much simpler to call the function


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);
}

Solution

  • ITYM

    typedef int (*ptrdef)(int,int);
    

    as your version is a function which returns an int * while you want a function pointer which returns an int.


    Just a hint: I know that the following is not common sense, but I prefer to typedef the function itself and then do

    typedef int myfunc(int,int);
    myfunc therealfunction; // bites me if I do a mistake
    int therealfunction(int a, int b)
    {
        // do stuff and
        return 42;
    }
    myfunc * funcptr = &therealfunction;
    

    in order to get bitten by an error instead of a warning if I accidentally change the declaration of therealfunction.