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

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


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

    int add(int*a,int*b);//pointer as function argument
    double add(double*a,double*b);//pointer as function argument
    

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

    #include<iostream>
    using namespace std;   
    int add (int*a,int*b);
    int main ()
    {
        int a,b,sum;
        cout<<"Enter the first number";
        cin>>a;
        cout<<"Enter the second number";
        cin>>b;
        sum=add(&a,&b);
        cout<<"The sum is "<<sum;
        return 0;
    }
    int add(int*a,int*b)
    {
        return *a+*b;
    }
    OUTPUT : Enter the first number 10
             Enter the second number 20
             sum is 30
    



Example : Write a program that swap the two number using the pointer as function argument .

    #include<iostream>
    using namespace std;   
    int add (int a,int b);
    int add (int*a,int*b);
    int main ()
    {
        int a,b;
        a=10;
        b=20;
        cout<<"\nBefore swap the value :";
        cout<<"\n a : "<<a;
        cout<<"\n b : "<<b;
        cout<<"\n After swap the value :";
        add(&a,&b);
        return 0;
    }
    int add(int*a,int*b)
    {
        int temp;
        temp=*a;
        *a=*b;
        *b=temp;
        cout<<"\n a : "<<*a;
        cout<<"\n b : "<<*b;
    }
    OUTPUT : Before swap the value :
             a : 10
             b : 20
             After swap the value :
             a : 20

    

Welcome to AndroidATPoint.

back image                     next image