Pointer-to-function-in c .

In this session i have discussed pointer to function in C .


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

    int(*add)();//pointer to function
    

Here * operator is with add which is a function name. And it did the same that we wanted to do. .


Example : Write a program that demonstrate the pointer to function .

    #includ<stdio.h> 
    int add();
    int main ()
    {
        int sum;
        int (*ptr)();
        ptr = &add;
        sum = (*ptr)();
        printf("The sum is %d",sum);
    }
    int add()
    {
        int a, b;
        printf("Enter first number");
        scanf("%d",&a);
        printf("Enter second number");
        scanf("%d",&b);
        return a+b;
    }

    
    OUTPUT : Enter the first number 10
             Enter the second number 20
             sum is 30
    


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

    #includ<stdio.h> 
    int add (int a,int b);
    int main ()
    {
        int sum;
        int a,b;
        a=20;
        b=10;
        int (*ptr)(int ,int);
        ptr = &add;
        sum = (*ptr)(a,b);
        printf("The sum is %d",sum);
    }
    int add(int a,int b)
    {
        return a+b;
    }
    OUTPUT : The sum is 30
    

Welcome to AndroidATPoint.

back image                     next image