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!
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
Compilers can produce warnings - make the compiler programmers happy: Use them!
Please don't PM me for help - and no, I don't do help over instant messengers.
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); }
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.
My homepage
Advice: Take only as directed - If symptoms persist, please see your debugger
Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"
Actually, I think the requirement of & was originally present, then removed because a function name by itself has no other meaning.
It is too clear and so it is hard to see.
A dunce once searched for fire with a lighted lantern.
Had he known what fire was,
He could have cooked his rice much sooner.