Function Pointer In C/C++

Share Your Love

We can create a pointer to any data type, including int, char, and float, and we can also make a pointer to a function. A function’s code always resides in the memory, implying that the function has an address. Using the function pointer, we can get the memory address.

function pointer in c cpp
Function Pointer In C/C++

Let’s see a simple example.

#include <stdio.h>
int main()
{
    printf("Address of main() function is %p",main);
    return 0;
}

The above code prints the address of a main() function.

Output:

Address of main() function is 0x455567

In the above output, we observe that the main() function has some address. Therefore, we conclude that every function has some address.

Declaration of a Function Pointer:

We’ve seen that functions have addresses, therefore we can create pointers that can contain these addresses and hence point to them.

Syntax of function pointer:

return_type (*ptr_name)(type1, type2…); 

For example:

int (*ip) (int);

In the above declaration, *ip is a pointer that points to a function that returns an int value and accepts an integer value as an argument.

float (*fp) (float);

In the above declaration, *fp is a pointer that points to a function that returns a float value and accepts a float value as an argument.

A function declaration is similar to a function pointer declaration, with the exception that the pointer is prefixed by a ‘*’. As a result, fp is declared as a function rather than a pointer in the above declaration.

We’ve learned how to specify the function pointer up to this point. The function pointer will now be assigned the address of a function.

float (*fp) (int , int);    // Declaration of a function pointer.
float func( int , int );    // Declaration of  function.
fp = func;                     // Assigning address of func to the fp pointer.  

In the above declaration, ‘fp’ pointer contains the address of the ‘func’ function.

Note: Declaration of a function is necessary before assigning the address of a function to the function pointer.

Note

Calling a Function Through a Function Pointer:

We already know how to use the standard method of calling a function. Now we’ll look at how to use a function pointer to call a function. 

Let’s say we want to declare a function like this:

float func(int , int);      // Declaration of a function.

Calling an above function using a usual way is given below:

result = func(a , b);     // Calling a function using usual ways.

Calling a function using a function pointer is given below:

result = (*fp)( a , b);  // Calling a function using function pointer.

Or

// Calling a function using function pointer, and indirection             // operator can be removed.
result = fp(a , b)

Calling a function by its name or by its function pointer has the same result. We can omit the indirection operator if we use the function pointer, as we did in the second case. Therefore, the indirection operator is used since it makes it plain to the user that we are utilizing a function reference.

Let’s understand the function pointer through an example.

#include <stdio.h>
int add(int,int);
int main()
{
   int a,b;
   int (*ip)(int,int);
   int result;
   printf("Enter the values of a and b : ");
   scanf("%d %d",&a,&b);
   ip=add;
   result=(*ip)(a,b);
   printf("Value after addition is : %d",result);
    return 0;
}
int add(int a,int b)
{
    int c=a+b;
    return c;
}  

Output:

Enter the values of a and b : 4
55
Value after addition is : 59

Passing a Function’s Address As An Argument to Other Function:

We can pass the function’s address as an argument to other functions in the same way we send other arguments to the function.

Let’s understand through an example.

include <stdio.h>
void func1(void (*ptr)());
void func2();
int main()
{
    func1(func2);
     return 0;
}
void func1(void (*ptr)())
{
    printf("Function1 is called");
    (*ptr)();
}
void func2()
{
    printf("\nFunction2 is called");
}  

In the above code, we have created two functions, i.e., func1() and func2(). The func1() function contains the function pointer as an argument. In the main() method, the func1() method is called in which we pass the address of func2.

When func1() function is called, ‘ptr’ contains the address of ‘func2’. Inside the func1() function, we call the func2() function by dereferencing the pointer ‘ptr’ as it contains the address of func2.

Output:

Function1 is called
Function2 is called

Array of Function Pointers:

In some situations when we don’t know which function will be called ahead of time, function pointers are employed. The addresses of different functions are stored in an array of function pointers, and the relevant function is called based on the index number.

#include <stdio.h>
float add(float,int);
float sub(float,int);
float mul(float,int);
float div(float,int);
int main()
{
    float x;              // variable declaration.
    int y;
    float (*fp[4]) (float,int); // function pointer declaration.
    fp[0]=add;  // assigning addresses to the elements of an array of a function   pointer.
    fp[1]=sub;
    fp[2]=mul;
    fp[3]=div;
    printf("Enter the values of x and y :");
    scanf("%f %d",&x,&y);
  float r=(*fp[0]) (x,y);        // Calling add() function.
    printf("\nSum of two values is : %f",r);
     r=(*fp[1]) (x,y);             // Calling sub() function.
    printf("\nDifference of two values is : %f",r);
      r=(*fp[2]) (x,y);            // Calliung sub() function.
    printf("\nMultiplication of two values is : %f",r);
     r=(*fp[3]) (x,y);           // Calling div() function.
    printf("\nDivision of two values is : %f",r);
    return 0;
}
float add(float x,int y)
{
    float a=x+y;
    return a;
}
float sub(float x,int y)
{
    float a=x-y;
    return a;
}
float mul(float x,int y)
{
    float a=x*y;
    return a;
}
float div(float x,int y)
{
    float a=x/y;
    return a;
}  

We’ve constructed an array of function pointers with the addresses of four functions in the code above. We use the function pointer to invoke the functions after saving their addresses in an array of function pointers.

Output:

Enter the values of x and y : 5
7
Sum of two values is : 12.000000
Difference of two values is : -2.000000
Multiplication of two values is : 35.000000
Division of two values is : 0.717658

Some Examples Of Function Pointer In C++

#include <iostream>
using namespace std;
int add(int a , int b)
{
    return a+b;
}
int main()
{
 int (*funcptr)(int,int);  // function pointer declaration
 funcptr=add; // funcptr is pointing to the add function
 int sum=funcptr(5,5);
 std::cout << "value of sum is :" <<sum<< std::endl;
  return 0;
}  

In the above program, we declare the function pointer, i.e., int (*funcptr)(int,int) and then we store the address of add() function in funcptr. This implies that funcptr contains the address of add() function. Now, we can call the add() function by using funcptr. The statement funcptr(5,5) calls the add() function, and the result of add() function gets stored in sum variable.

Output:

value of sum is : 10

Let’s look at another example of a function pointer.

#include <iostream>
using namespace std;
void printname(char *name)
{
    std::cout << "Name is :" <<name<< std::endl;
}
int main()
{
    char s[20];  // array declaration
    void (*ptr)(char*);  // function pointer declaration
    ptr=printname;  // storing the address of printname in ptr.
    std::cout << "Enter the name of the person: " << std::endl;
    cin>>s;
    cout<<s;
    ptr(s);  // calling printname() function
   return 0;
} 

Output:

Enter the name of the person: John
John
Name is :John

We define the function printname() in the above program, which takes a char pointer as a parameter. The function pointer is declared as void (ptr)(char). We are setting the address of the printname() function to ptr with the expression ptr=printname. We can now use the ptr statement to call the printname() method (s).

Pointers as Function Argument in C/C++:

Pointer as a function parameter is used to hold addresses of arguments passed during the function call. This is also known as call by reference. Any modification to the reference variable will affect the original variable when a function is called by reference.

Example Time: Swapping two numbers using Pointer:

#include <stdio.h>
void swap(int *a, int *b);
int main()
{
    int m = 10, n = 20;
    printf("m = %d\n", m);
    printf("n = %d\n\n", n);
    swap(&m, &n);    //passing address of m and n to the swap function
    printf("After Swapping:\n\n");
    printf("m = %d\n", m);
    printf("n = %d", n);
    return 0;
}
/*
    pointer 'a' and 'b' holds and
    points to the address of 'm' and 'n'
*/
void swap(int *a, int *b)
{
    int temp;
    temp = *a;
    *a = *b;
    *b = temp;
}

Output:

Before Swapping
m = 10
n = 20
After Swapping:
m = 20
n = 10

Functions returning Pointer variables:

A function can also return a pointer to the calling function. In this case, you must be careful, because local variables of function don’t live outside the function. They have scope only inside the function.

Hence if you return a pointer connected to a local variable, that pointer will be pointing to nothing when the function ends.

#include <stdio.h>
int* larger(int*, int*);
void main()
{
    int a = 15;
    int b = 92;
    int *p;
    p = larger(&a, &b);
    printf("%d is larger",*p);
}
int* larger(int *x, int *y)
{
    if(*x > *y)
        return x;
    else
        return y;
}

Output:

92 is larger

Safe ways to return a valid Pointer:

  • Either use argument with functions. Because argument passed to the functions are declared inside the calling function, hence they will live outside the function as well.
  • Or, use static local variables inside the function and return them. As static variables have a lifetime until the main() function exits, therefore they will be available througout the program.

Share Your Love
Avatar photo
Lingaraj Senapati

Hey There! I am Lingaraj Senapati, the Founder of lingarajtechhub.com My skills are Freelance, Web Developer & Designer, Corporate Trainer, Digital Marketer & Youtuber.

Articles: 355

Newsletter Updates

Enter your email address below to subscribe to our newsletter