×

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++ Constructor

Constructor is a specific method in C ++ that is automatically called when an object is created. Typically, it is used to set the data members of a new object....

4 minutes read.

Substring in C++

A substring is a function in c++ that is imported from the string library. An element of a string is called a substring. A substring contains two parameters length and...

2 minutes read.

Factorial Program in C++

C++ Factorial Program: The product of all positive descending integers is the factorial of n. n! denotes the factorial of n. For instance: 5! = 5*4*3*2*1=120 4! = 4*3*2*1=24 In Combinations and Permutations, the...

4 minutes read.

getline() Function and Character Array in C++

In this article, we will explore about some concepts on getline() function and character array in the most useful language C++. The getline() method in C++ is simply a standard library...

6 minutes read.

Division in C++

C++ Division Arithmetic Operation In C++ the arithmetic operator / is used for division. This operator takes two operands and returns the result of dividing the left operand by the right...

3 minutes read.

C++ | C Plus Plus Data type

Data type in every language is very important. Data type means the different kinds of data that are supported by a particular programming language. A computer language’s data types specify the...

15 minutes read.

How to concatenate two strings in C++

In the C++ programming language, the concatenation of two or even more strings is covered in this section. The term "string concatenation" refers to a collection of characters that join two...

4 minutes read.

Virtual Function Vs Pure Virtual Function

Virtual activity is a member function defined in the foundation phase that can be redefined by acquired classes. Let's have a look at an example: #include <iostream>   #include <bits/stdc++.h> #include <stdlib> using namespace std;   class Base   {    ...

5 minutes read.

Sizeof() Operators in C++

sizeof() Operators in C++ The sizeof() operator in C++ defines the size of variables, constants, or data types. It is a unique operator that manipulates other operators and returns the size...

4 minutes read.

C++ Data Abstraction

Object-oriented programming (OOP) provides a number of characteristics that enable programmers to design programmes based on a variety of ideas, reducing errors and increasing program flexibility. The abstraction of data...

7 minutes read.

Classes and Objects in C++

When it comes to object-oriented programming, objects are the basic building blocks. Memory is taken up by objects, which contain data and methods or functions that operate on it. On...

3 minutes read.

Print Table Using For-loop in C++

Multiplication Table In mathematics, a table is created by multiplying a certain number by all of the counting numbers, i.e., 1, 2, 3, 4, 5, 6, and so on. It is...

3 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.

How to find the length of the vector in C++

Like dynamic arrays, vectors can automatically adjust their size when an element is added or removed, and the container manages its storage. Because vector items are stored in contiguous storage, iterators...

3 minutes read.

How the value is passed in C++

Introduction: The call-by-value method of giving arguments to a function duplicates the real value of an argument into the formal parameter of the function. In this instance, modifications to the parameter...

5 minutes read.

Storage Classes in C

Storage Classes in C Storage Classes are used to define the variable and function property. These functionalities include basically the scope, accessibility, and lifetime that help us detect the existence of...

4 minutes read.

C++ Program to move all zeros to the end of the array

Write a program to move all the zeros in the arr[] to the end. The order of the non-zero elements should not be altered and all the zeros should be...

3 minutes read.

C++ Expressions

C ++ equations are made up of operators, constants and variables arranged according to language rules. It may also include function calls that give results. To calculate the value, the...

4 minutes read.

C++ Bitwise XOR Operator

Exclusive OR is another name for the bitwise XOR operator. The ‘^’ is used to indicate it. It operates at the bit level of the operands, as the name implies....

4 minutes read.

Swap numbers in C++

Swap numbers Swapping refers to interchanging values between two variables. Swapping is important and easy to understand programming logic in the world of coding. Though it is used in the programming...

4 minutes read.