Weird pointer to function



 DEVELOP > c-Plus-Plus > Weird pointer to function

LINK TO THIS PAGE  


rating :  0   |  0


  Page 1 of 1

1

 
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
.


  Page 1 of 1

1

 


Related Articles
 

NEWER

pg.1232     pg.940     pg.716     pg.544     pg.412     pg.311     pg.234     pg.175     pg.130     pg.96     pg.70     pg.50     pg.35     pg.24     pg.16     pg.10     pg.6     pg.3     pg.1

OLDER