
- Forum
- Programming Talk
- C and C++
- function
function
This is a discussion on function within the C and C++ forums, part of the Programming Talk category; how can a function be passed as a argument in another function......in c as well as c++...
-
12-25-2010, 07:19 AM #1
- Join Date
- Dec 2010
- Answers
- 32
function
how can a function be passed as a argument in another function......in c as well as c++
-
you can do so by using pointer to function (function pointers)...
Declare a function pointer as though you were declaring a function
void (*ptofn)(int);
In this example, ptofn is a pointer to a function taking one argument, an integer, and that returns void. It's as if you're declaring a function called "*ptofn", which takes an int and returns void. Now, if *ptofn is a function, then ptofn must be a pointer to a function. (Similarly, a declaration like int *x can be read as *x is an int, so x must be a pointer to an int.)
To initialize the function pointer, you must assign it the address of a function in your program, as follows:
HTH!!!Code:#include <stdio.h> void myfunc(int x) { printf( "%d\n", x ); } int main() { void (*ptofn)(int); ptofn = &myfunc; //pointer to function //now you could pass ptofn to any other function as a parameter so that you could invoke myfunc like this ptofn(10); //this would call myfunc and print out 10 return 0; }
-
pass by value and pass by reference
-
Sponsored Ads

Reply With Quote





