Fuction pointers - Is this legal C?

D

David Scarlett

Can anyone tell me whether the following is legal C?

int foo(int);
int bar(int (*)(int));

int main(void)
{
int x;

x = bar(&foo);

return 0;
}

int bar(int (*foo)(int))
{
/* ... */
}



I had some similar code which compiled fine using 'gcc -Wall', but I'm
concerned about what would happen if I called 'foo' from withing 'bar'.
Would it use the pointer it is passed, or the function declared at the
start, if they were different functions? Or is this undefined
behaviour? What if I used the dereferencing operator when calling foo?

I've changed the name of the pointer 'bar' recieves just to be safe,
but I'm still curious as to what the effects of this sort of code would
be...


Thanks.
 
K

Kip Neuhart

David Scarlett said:
Can anyone tell me whether the following is legal C?

Would it use the pointer it is passed, or the function declared at the
start, if they were different functions? Or is this undefined
behaviour? What if I used the dereferencing operator when calling foo?

The global name is hidden by the local parameter name. Any references to foo
will act on the parameter, which is standard and correct behavior. It
doesn't matter at all whether you dereference the pointer when calling foo
(except for older compilers that require it), both are allowed and will
still reference the parameter.
 
B

Barry Schwarz

Can anyone tell me whether the following is legal C?

int foo(int);
int bar(int (*)(int));

int main(void)
{
int x;

x = bar(&foo);

The & is unnecessary. A function name without the parenthesized
argument list is the syntactical representation of the address of the
function.
return 0;
}

int bar(int (*foo)(int))
{
/* ... */
}



I had some similar code which compiled fine using 'gcc -Wall', but I'm
concerned about what would happen if I called 'foo' from withing 'bar'.
Would it use the pointer it is passed, or the function declared at the
start, if they were different functions? Or is this undefined
behaviour? What if I used the dereferencing operator when calling foo?

I've changed the name of the pointer 'bar' recieves just to be safe,
but I'm still curious as to what the effects of this sort of code would
be...


Thanks.



<<Remove the del for email>>
 

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
474,141
Messages
2,570,817
Members
47,367
Latest member
mahdiharooniir

Latest Threads

Top