×

Returning a Function Pointer from a Function in C/C++

Pointers to functions can be used in the C programming language just like standard data pointers such as "int *," "char *," etc.

The following is a basic example of a function pointer definition and a function call.

Example

#include <stdio.h>
void funct(int x){
	printf(“Value of x is %d\n”,x);
}
int main(){
	/* funct_ptr is a pointer to the function funct() */
void (*funct_ptr)(int) = &funct;
/* Calling funct() using funct_ptr pointer */
	(*funct_ptr)(99);
	return 0;
}

Output:

Returning a function pointer from a function in C/C++

Take a look at the statement "void (*funct ptr)(int)." If we remove the parentheses surrounding "*funct ptr," we get "void *fun ptr(int)," which is a function declaration that returns a void pointer.

A function pointer, unlike a conventional pointer, points to code rather than data. A function pointer typically holds the beginning of executable code. Unlike conventional pointers, function pointers do not allocate or de-allocate memory.

The name of a function can be used to obtain the address of a function.

Program Code:

Consider the following example: Here, the "&" address operator is removed from the assignment.

We also altered the function call by eliminating the "*," but the code still works.

 #include<stdio.h>
void funct(int x){
	printf(“Value of x is %d\n”,x);
}
int main(){
	/* “&” operator removed */
	void (*funct_ptr)(int) = funct;
	/* “*” removed */
	funct_ptr(99);
	return 0;
}

Output:

Returning a function pointer from a function in C/C++

An array (collection) of function pointers can be used in the same way that conventional pointers are.

In place of the switch case, a function pointer might be used.

Example: In the following application, for example, the user is given an option between zero and two to complete several tasks.

#include <stdio.h>
void add(int x, int y){
	printf(“Sum of %d and %d is %d\n”,x,y,x+y);
}
void sub(int x, int y){
	printf(“Difference of %d and %d is %d\n”,x,y,x-y);
}
void multiplication(int x, int y){
	printf(“Multiplication of %d and %d is %d\n”,x,y,x*y);
}
int main(){
	/* funct_ptr_arry is an array (collection) of function pointers */ 
	void (*funct_ptr_arry[])(int, int) = {add, sub, multiplication};
    	unsigned int abc, x = 10, y = 20;
 	printf("Enter Choice: 0 for addition, 1 for subtraction and 2 for
multiplication\n");
scanf("%d", &abc);
  	if (abc > 2) return 0;
  	(*funct_ptr_arry[abc])(x, y);
return 0;
}

Output:

Returning a function pointer from a function in C/C++

A function pointer, just like a normal data pointer, can be provided with an argument and returned from a function.

Example: Look at the following C program example, in which wrapper() takes a void funct() argument and calls the provided function.

#include <stdio.h>
void funct1(){
	printf(“Function1\n”);
}
void funct2(){
	printf(“Function2\n”);
}
void wrapper(void (*funct)()){
	funct();
}
int main(){
	wrapper(funct1);
	wrapper(funct2);
	return 0;
}

Output:

Returning a function pointer from a function in C/C++

This specific idea is quite useful in C. To reduce code duplication, we can utilize function pointers in C. In the case of an array of structures, for example, a simple qsort() method could be used to sort arrays (collections) in any order, ascending or descending. Furthermore, with function pointers and void pointers, the qsort() method can be used for any data type.

Example

#include <stdio.h>
#include <stdlib.h>
int compare (const void *x, const void *y){
	return  ( *(int*)x - *(int*)y);
}
int main(){
	int arry[] = {12, 5, 61, 57, 100, 78};
	int m = sizeof(arry)/sizeof(arry[0]), n;
	qsort (arry, m, sizeof(int), compare);
	for (n=0; n<m; n++){
     		printf ("%d ", arry[n]);
	}
  	return 0;
}

Output:

Returning a function pointer from a function in C/C++

We may develop our own methods, similar to qsort(), that can be applied to any data type and can perform several jobs without code duplication.

Program Code:

A search function for just any data type is shown below. In fact, by developing a customized comparison function, we can utilize this search method to identify nearby components (below a threshold).

#include <stdio.h>
#include <stdbool.h>
bool comparison (const void * x, const void * y){
return ( *(int*)x == *(int*)y );
}
int search(void *arry, int arry_size, int element_size, void *m,
           bool comparison (const void * , const void *)){
char *ptr = (char *)arry;
int a;
for (a=0; a<arry_size; a++){
     	if (comparison(ptr + a*element_size, m)){
                  return a;
	}
}
/* If element 	is not found */
  	return -1;
}
  


int main(){
    int arry[] = {1, 3, 50, 44, 98, 101};
    int n = sizeof(arry)/sizeof(arry[0]);
    int m = 44;
    printf ("Returned index is %d ", search(arry, n, sizeof(int), &m, comparison));
    return 0;
}

Output:

Returning a function pointer from a function in C/C++

In C++, many object-oriented features are implemented via function pointers available in C.


Related Topics

C++ Fork

A new process known as a "child process" is created with the fork system function and runs concurrently with the process that invoked fork() (parent process). Both processes will carry...

4 minutes read.

Inheritance and Friendship in C++

In this tutorial, we will look into what Inheritance and Friendship in C++ are, as well as the differences between the two. What is Inheritance in C++: In C++, inheritance is an...

2 minutes read.

Single level Inheritance

Inheritance is a fundamental element of C++’s Object-Oriented Programming (OOP). It allows a class (called the derived class) to inherit characteristics and attributes from another class (called the base class)....

5 minutes read.

C++ int into String

Data type conversion is a standard editing process. You may need to convert variable from one type of data to another in a variety of situations. There are two ways...

5 minutes read.

Pointer to Object in C++

What is a pointer? A pointer in C++ is used to point the variable by storing the address of the variable. In C++, to print the address of the variable, we...

4 minutes read.

Parameterize Constructor

C++ Parameterized Constructor A constructor having parameters is known as parameterize constructor. Parameterize constructor is used to assign different values. Syntax: className(data-type argument){   // Constructor definition   }   className(data-type argument, data-type argument){   // Constructor definition   } A parameterized constructor can be passed values to constructor function in two ways: 1)...

1 minute read.

Vector in C++

Vector in C++ In today’s article, we will be learning all the things about vector in C++ and how vector is different form an array in C++. So basically, vector is very...

3 minutes read.

C++ Queue

C++ queue: Queue in C++ is also a container adapter with the functionality of a queue. Queue is just the opposite of the stack in C++ because stack works on...

4 minutes read.

Bitwise Operator vs Logical Operator

Bitwise Operator  Bitwise operators perform operations bit by bit on bits.The value is converted to abinary during operations like addition, subtraction, division, and so on. These operations are carried out at the...

3 minutes read.

gmtime() function in C/C++

C++ language is used to make high-performance applications that can work efficiently. It is one of the world's most popular languages. It is an object-oriented and high-level programming language, which...

4 minutes read.

C++ Enumeration

C++ Enumeration In C++, Enum is a special data type that contains some fixed sets of components that have various applications in the programming. Enum works fine with fixed constant sets...

3 minutes read.

C++ Program to find the element that occurs once

Write a program to find the element in the array that occurs once. Given that all the numbers in the array are present two times and the array is sorted,...

7 minutes read.

C++ add two numbers using the function

Here we will learn how to add two numbers by creating function in C++. Let’s learn this with help of example. Code: - #include <iostream> using namespace std; int add_two_no(int a, int b); int main(){   int...

1 minute read.

C++ Friend Functions

In C++, friends are special functions that are not a part of a class yet have access to its private and protected members. The friend keyword is used to declare...

4 minutes read.

std::min in C++

std::min in C++ std::min is specified in the program code, used to calculate the lowest amount that has been transferred. When there's more of someone who returns first of them. It's used...

2 minutes read.

Differences between #define & const in C/C++

 Differences between #define & const in C/C++ A preprocessor directive is #define. The preprocessor replaces things defined by #define prior to starting compilation. In this chapter, we'll learn about the member, variable,...

3 minutes read.

Converting string into integer in C++

When programming in C++, we'll frequently need to change one data type to another. When we use C++ to create apps, we must transform data from one type to another. When...

7 minutes read.

C++ Algorithms

There are plenty of programming paradigms that are closely associated with the implementations of code and simulate them into a proper functional one. This is done with the help of...

5 minutes read.

C++ vardiac() function

In the C++ programming language, the flexibility feature is provided by the variadic function. To understand more about flexibility, let's see the following syntax. Syntax: If we have to add two numbers,...

3 minutes read.

C++ Fibonacci Series

What is a Fibonacci series? A Fibonacci series or sequence is a very popular programming paradigm. The next element occurring in the N terms series is determined by the sum of...

2 minutes read.