For function pointer "fptr",why is value of "fptr" and *fptr same?What *fptr even mean?I only knew (*fptr)() or fptr()

11,982

A pointer is to point to a memory location. A function is in memory and has a starting address. You can very well dereference the function name(which is a pointer) to obtain the function at that address.

From, Stephen Prata "Cpp Primer Plus"


History Versus Logic Holy syntax!


How can pf and (*pf) be equivalent? One school of thought maintains that because pf is a pointer to a function, *pf is a function; hence, you should use (*pf)() as a function call. A second school maintains that because the name of a function is a pointer to that function, a pointer to that function should act like the name of a function; hence you should use pf() as a function call. C++ takes the compromise view that both forms are correct, or at least can be allowed, even though they are logically inconsistent with each other. Before you judge that compromise too harshly, reflect that the ability to hold views that are not logically self-consistent is a hallmark of the human mental process.

Share:
11,982
Thokchom
Author by

Thokchom

Bear with me, I am a slow learner, but I am sincere and really interested to learn programming.

Updated on June 28, 2022

Comments

  • Thokchom
    Thokchom almost 2 years

    Why is a function pointer behaving like an array pointer as far as this behavior goes?I mean, let's begin with the case of an array list[] where we'll consider &list and list.

     char name[5]= "Eric",(*aptr)[5]=&name;
     printf("%p,%p",*aptr,name); //BOTH ARE NUMERICALLY SAME
    

    and we can refer to array elements also as (*aptr)[1],(*aptr)[2], etc.I understand what's going on here.

    But why is the same working for functions?After all a "function" as such is not a contiguous memory block of similar elements as an array is.Consider this.

    Suppose fptr is a function pointer as in my program.Why does fptr and *fptr give the same value when printed?What does *fptr even mean?I only knew that we can invoke a function using its pointer as (*fptr)() or as fptr(),but what is *fptr alone then?

    #include<stdio.h>
    
    void foo(){};
    
    int main(void)
    {
    void (*fptr)()=foo;
    printf("%p,%p",fptr,*fptr);
    
    }
    

    Result- 00401318 00401318