| Topic: |
DEVELOP > c-Plus-Plus |
| User: |
"Frederick Dean" |
| Date: |
02 Sep 2006 10:33:35 PM |
| Object: |
Weird pointer to function |
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!
.
|
|
| User: "Heinz Ozwirk" |
|
| Title: Re: Weird pointer to function |
03 Sep 2006 02:45:10 AM |
|
|
"Frederick Dean" <dingweixp@tom.com> schrieb im Newsbeitrag
news:eddjm9$j2a$1@news.cn99.com...
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
.
|
|
|
|

|
Related Articles |
|
|