Accessing a function pointer without parentheses

I have this code:

#include <stdio.h>

int getAns(void);
int num;

int main() 
{
    int (*current_ans)(void);
    current_ans = &getAns;
    // HERE
    printf("%d", current_ans());    

}

int getAns()
{
    return num + 3;
}

      

However, is it possible to have something in place // HERE

that allows the next line printf("%d", current_ans);

to access getAns () in a workaround?

+2


source to share


4 answers


I suspect you cannot, because you ()

need to tell the compiler that this is a function call. However, if you really want to do this, you can do:



#define current_ans current_ans()

      

+5


source


Although I agree with pierr's answer,

#define current_ans current_ans()

      



will make the code very hard to read

+6


source


How about "#define current_ans myRoundaboutFnName ()"

+1


source


No, because current_ans

both current_ans()

are different things. Without parentheses, both current_ans

and getAns

are function pointers, and in parentheses are function calls. If you think of parentheses as dereferencing a pointer by executing the code, basically what you are asking is to treat the pointer and the contents of the pointer as one.

+1


source







All Articles