Exforsys
+ Reply to Thread
Results 1 to 3 of 3

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++...

  1. #1
    Manyamanas is offline Member Array
    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++


  2. #2
    techvinny is offline Moderator Array
    Join Date
    Dec 2010
    Answers
    56
    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:

    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;
    }
    HTH!!!


  3. #3
    dokepriya is offline Junior Member Array
    Join Date
    Jan 2011
    Answers
    1
    pass by value and pass by reference


    •    Sponsored Ads



Latest Article

Network Security Risk Assessment and Measurement

Read More...