What exactly does that second parameter mean? I have never seen such an argument before.Code:void traverse (link h, void (*visit)(link)) {
if (h == NULL) {
(*visit)(h);
traverse(h->next, visit);
}
}
Printable View
What exactly does that second parameter mean? I have never seen such an argument before.Code:void traverse (link h, void (*visit)(link)) {
if (h == NULL) {
(*visit)(h);
traverse(h->next, visit);
}
}
A pointer to a function.
It might look like:
See http://www.newty.de/fpt/index.htmlCode:void myfunction(link x)
{
return;
}
/* ... */
/* call traverse */
traverse(h, &myfunction);
/* ... */
I get your example, because i have used functions that way before.
But I don't get what (*visit)(h) is. Does it mean the function visit is pointing to the h node
One can also write:
EDIT:Code:traverse(h, myfunction);
visit is a function pointer, so it is just calling the function and passing h as the argument. You can also write visit(h).Quote:
But I don't get what (*visit)(h) is. Does it mean the function visit is pointing to the h node
Calls what's pointed to by visit with the parameter h.
No need to dereference, it's the same as
Basically,Code:visit(h);
Code:traverse(h, myfunction); /* short way */
traverse(h, &myfunction); /* long way */
Both are correct.Code:visit(h); /* short way */
(*visit)(h); /* long way */
Thanks guys.
My lecturer seems intent on confusing people to no end, but then again perhaps it's a good thing I learnt this style of coding. Pretty easy then.
Thanks zacs7 and laserlight =)
Writing the formmakes sure that it's CLEAR that visit is a funciton pointer - it's not needed, and I don't use that form when I use function pointers - but it is valid, and offers a slightly higher degree of "explaining what is going on" (assuming of course you can follow it).Code:(*visit)(h);
--
Mats
The trade off of this slightly higher degree of explanation is that it delves into the details. I think that taking a typedef and then using "normal" function call syntax makes for a higher level of abstraction instead, e.g.,Quote:
makes sure that it's CLEAR that visit is a funciton pointer - it's not needed, and I don't use that form when I use function pointers - but it is valid, and offers a slightly higher degree of "explaining what is going on" (assuming of course you can follow it).
Incidentally, h == NULL looks like it should be h != NULL instead since h->next would result in the dereferencing of a null pointer if h == NULL.Code:typedef void (*VisitFunction)(link);
void traverse(link h, VisitFunction visit) {
if (h == NULL) {
visit(h);
traverse(h->next, visit);
}
}