×

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

System() function in C++

As a part of the c/c+ standard library, the system() function passes commands to be executed by the operating system’s command processor or terminal and returns the completed command. We...

2 minutes read.

Top 14 Best Free C++ IDE (Editor & Compiler) for Windows in 2024

Bjarne Stroustrup created the all-purpose object-oriented programming language C++. To develop C++ programs, there are various Integrated Development Environments (IDE) that offer prewritten code templates. These programs automatically modify the...

6 minutes read.

Templates in C++ vs Generics in Java

As the title suggests, there is no rivalry or there is no cut comparison between generics and templates in Java and C++, respectively. The main aim of this article is...

4 minutes read.

Inheritance in C++ vs Java

Just like we inherit traits from our parents, object-oriented programming has a concept called inheritance. In terms of object-oriented programming, a class's traits and behaviours, or its data and methods,...

4 minutes read.

Const Keyword in C++

The const programming language keyword will be covered in this section. The constant value that cannot change during program execution is defined using the const keywords. It implies that once...

9 minutes read.

Binary Search in C++

The binary search in the C++ programming language will be discussed. By continually halves the array and then seeking specified items from a half array; binary search is a technique...

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

How to Declare Unordered Sets in C++

The implementation of an unordered set using a hash table ensures that the insertion is always randomised by hashing the keys into hash table indices. When we define keys of...

4 minutes read.

While Loop Examples in C++

While Loop A while loop repeats all code in its body, also known as a while statement, as long as a specific condition is satisfied. The loop ends if or when...

4 minutes read.

C++ Tricks for Competitive Programming

If you are interested in Computer science or Information technology, you must have heard about competitive programming. Competitive programming is a way to improve your problem-solving skills. There are various...

7 minutes read.

Char Array to String in C++

Regardless of the programming language you use, data structure is critical to the success of your project. Although each programming language has its own collection of data structures, C++ contains a...

4 minutes read.

Copy elision in C++

The Copy Omission is another name for the Copy Elision. One of the several compiler optimization techniques is copy elision. It prevents items from being copied inadvertently. This Copy Elision approach...

3 minutes read.

Diamond Pattern Using Do-While loop in C++

What is Do-While Loop? An iterative loop that checks the condition at the end.The Do-While loop can be used whenever a test condition is specific, as the control enters the loop...

5 minutes read.

Array of Object in C++

What is an Array? In C++, an array is a group of related data types, such as int, char, float, double, etc., that are easily accessed by index value alone and...

12 minutes read.

C++ String Class and its Applications

The String class is available in C++. The character array is represented by the C string. The string class in C++ has a few different attributes. It contains several functions...

4 minutes read.

Learn C++ Tutorial

C++ Introduction C++ is an object-oriented programming language. It was developed by Bjarne Stroustrup at AT&T Bell Laboratories. It is superset (extension) of C programming language. Depending upon features supported by programming...

10 minutes read.

Timsort Implementation Using C++

Timsort Implementation Using C++ The Timsort is a stable sorting algorithm that uses the idea of merge sort and insertion sort. It can also be called a hybrid algorithm of insertion...

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.

User-defined literals in C++

Introduction to User-Defined Literals: User-defined literals, introduced in C++11, are a way to extend the C++ language to allow users to define their literal suffixes and the corresponding behavior. These suffixes...

7 minutes read.

C++ String Concatenation

C++ String Concatenation In this section, we will learn about C ++ String Concatenation, what it does, how it works, and will also see its programs. What is the String Concatenation? The + operator...

3 minutes read.