function-as-a-function-argument-in c++ .

In this session i have discussed function as a function in C++ .


We will know the function as function argument lets see the below code this is the way by which you can declare the function as a function argument .


Syntax

type function_name(type(*function_name)(parameter list));
int operation(int(*function)(int ,int));//function as function argument
    

Example : Write a program that demonstrate the function as function argument .

    #include<iostream>
    using namespace std;  
    void print()
    {
        cout<<"Hello World";
       
    }
    void Function(void (*f)())
    {
            (*f)();
    }
    int main()
    {
        Function(print);
        return (0);
    }
    OUTPUT : Hello World 
    


Example : Write a program that demonstrate the function as function argument .

    #include<iostream>
    using namespace std;  
    void printNumber(int i)
    {
        cout<<i;
        cout<<" ";
    }
    void Function(void (*f)(int))
    {
        int i;
        for( i = 1; i <= 5; i++)
        {
            (*f)(i);
        }
    }
    int main()
    {
        Function(printNumber);
        return (0);
    }
    OUTPUT : 1 2 3 4 5 
    

Example : Write a program that demonstrate the function as a function argument .

    #include<iostream>
    using namespace std;   
    int add (int a,int b);
    int sub(int a,int b);
    int operation(int(*function)(int ,int),int a,int b)
    {
        return ((*function)(a,b));
    }
    int main ()
    {
        int a,b,a,s;
        a=10;
        b=20;
        a=operation(add,a,b);
        cout<<"Sum : "<<a;
        s=operation(sub,a,b);
        cout<<"Sub : "<<s;
        return 0;
    }
    int add(int a,int b)
    {
        return(a+b);
    }
    int sub(int a,int b)
    {
        return(a-b);
    }

    OUTPUT : Sum : 30
             sub : 10    

Welcome to AndroidATPoint.

back image                     next image