I cant find any example that shows how it works and what are is advantages.
What you mean by passing a function as argument to another function? How does it work?
Thanks!
Printable View
I cant find any example that shows how it works and what are is advantages.
What you mean by passing a function as argument to another function? How does it work?
Thanks!
Look up the standard qsort function in the help/google. It takes a compare function.
As to why you would want to do that, there are plenty of different reasons why you would want that:
1. Flexibility - in the qsort case, it can sort ANY type of data that you can compare in an orderable fashion (and that is entirely up to you - it can be integers, strings, dates (in any format), book structures by number of pages, book structures by ISBN, book structure by author, etc, etc).
2. User supplied functions - for example the Windows API supports "callback" functions, which is called under defined circumstances, e.g. certain events happen.
3. Table-driven programming - a function is used to supply what to do when (for example) a value in a table matches some input data (e.g. parsing commands).
4. Dynamic support for different options (e.g. different formatting, different hardware devices, etc, etc).
This is not a conclusive list of what function pointers/functions as parameters are used for.
--
Mats
How do you do it? Passing is easy:
func(&function);
Declaring a function to take a pointer to a function is less trivial, but something along the lines of:
typedef return_type (name)(argument_type argument_name);
void foo(name* pFunction);
Oh? Do elaborate.
You don't take the address of function names.
It works either way and if you have to do it with members of a class, then I'd rather do it with global functions, as well (if I'm reading you correctly).
Both work.Code:void foo2();
typedef void (fooptr)();
void foo(fooptr* p) { }
int main()
{
foo2(&foo);
foo2(foo);
}
What is this class thing you speak of?
C++-ish:
Code:class CFoo
{
public:
void foo();
}
typedef void (CFoo::* fooptr)();
void foo(fooptr p) { }
int main()
{
foo(&CFoo::foo); // OK
foo(CFoo::foo); // Illegal.
}
Hmm that doesn't look like legal c code...
Indeed not, it's C++.
But the point was that if I have to use & on variables, and on member functions in classes, then why should I not do it on global functions?
Both the examples with & and without compiles in both C and C++, so I prefer to use the &.
Older versions of VC didn't allow the & in front of the function name, but newer versions do, and I believe it has to do with standards compliance.
In C++ you can use function references. Much nicer since you never need to check for NULL.
I believe the ability to pass a function without & is for backwards compatibility only.
Actually, I think the requirement of & was originally present, then removed because a function name by itself has no other meaning.
Well, one of them is there for backwards compatibility, but as long as it works...