Weird pointer to function

F

Frederick Dean

Hi, guys!
Please look at the very simple code below:
//---------------code begin------------------------
void f()
{

cout << "f function " << endl;
}

void (*pf)() = &f;

int main()
{
int *p;
pf();
(*pf)();
cout << std::hex << *pf << endl;
cout << pf << endl;
cout << **pf << endl; // also works, oh....
cout << *******pf << endl; // also works, Weird.
(*************pf)(); // also works in most compilers, why??
return 0;
}
//----------------code end---------------------------

I wonder why (**********pf)() still works? Even any number of '*'
before pf will work too.

Any help is appreciated!
Thanks!
 
H

Heinz Ozwirk

Frederick Dean said:
Hi, guys!
Please look at the very simple code below:
//---------------code begin------------------------
void f()
{

cout << "f function " << endl;
}

void (*pf)() = &f;

int main()
{
int *p;
pf();
(*pf)();
cout << std::hex << *pf << endl;
cout << pf << endl;
cout << **pf << endl; // also works, oh....
cout << *******pf << endl; // also works, Weird.
(*************pf)(); // also works in most compilers, why??
return 0;
}
//----------------code end---------------------------

I wonder why (**********pf)() still works? Even any number of '*'
before pf will work too.

There is a standard conversion from "function" to "pointer to function". So
you can use a function wherever a pointer to a function is required. That
might be the reason why you can dereference a pointer to a function as often
as you like. With that in mind and

typedef void (*T)();
T pf = f; // No need to explicitly take the address of f
(***pf)();

the last statement becomes something like

(*(T*)*(T*)*pf)();

Perhaps someone else can quote the relevant parts of the standard, but
basically, you get a pointer to a function when you dereference a pointer to
a function. Functions, like C-style arrays, behave a little bit different
than proper objects.

HTH
Heinz
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,780
Messages
2,569,614
Members
45,287
Latest member
Helenfem

Latest Threads

Top