Function Pointer In C

Function Pointer In C

Function pointers are a powerful feature of the C language that allows you to store and call functions through pointers.

#include <stdio.h> 
// A normal function with an int parameter 
// and void return type 
void fun(int a) 
{ 
    printf("Value of a is %d\n", a); 
} 
  
int main() 
{ 
    // fun_ptr is a pointer to function fun()  
    void (*fun_ptr)(int) = &fun; 
  
    /* The above line is equivalent of following two 
       void (*fun_ptr)(int); 
       fun_ptr = &fun;  
    */
  
    // Invoking fun() using fun_ptr 
    (*fun_ptr)(10); 
  
    return 0; 
} 

Output

Value of a is 10

Interesting facts about function pointers

  1. Function pointers in C do indeed point to code, not data. They store the memory address of the executable code of a function, allowing you to call that function dynamically at runtime. This is a fundamental distinction between function pointers and regular data pointers, which point to data in memory. Function pointers are a powerful feature in C that enables dynamic and flexible function invocation
  1. Function pointers are used to reference and call functions, not to allocate or deallocate memory. Memory allocation and deallocation are typically performed using data pointers, such as those returned by functions like malloc and free.
  2. In C, you can obtain a function’s address by simply using the function’s name without the address operator &. This is because the name of a function, when used in an expression (without parentheses), automatically converts to a function pointer. So, you can call a function using the function’s name without needing to use the dereference operator *.

#include <stdio.h> 
// A normal function with an int parameter 
// and void return type 
void fun(int a) 
{ 
    printf("Value of a is %d\n", a); 
} 
  
int main() 
{  
    void (*fun_ptr)(int) = fun;  // & removed 
  
    fun_ptr(10);  // * removed 
  
    return 0; 
}

Output

Value of a is 10

4. Function pointers can indeed be used to create an array of pointers to functions, which allows for dynamic function dispatch, similar to a switch-case statement. This can lead to more flexible and maintainable code, as you can choose which function to execute at runtime based on user choices or other conditions.

#include <stdio.h> 
void add(int a, int b) 
{ 
    printf("Addition is %d\n", a+b); 
} 
void subtract(int a, int b) 
{ 
    printf("Subtraction is %d\n", a-b); 
} 
void multiply(int a, int b) 
{ 
    printf("Multiplication is %d\n", a*b); 
} 
  
int main() 
{ 
    // fun_ptr_arr is an array of function pointers 
    void (*fun_ptr_arr[])(int, int) = {add, subtract, multiply}; 
    unsigned int ch, a = 15, b = 10; 
  printf("Enter Choice: 0 for add, 1 for subtract and 2 "
            "for multiply\n"); 
    scanf("%d", &ch); 
  
    if (ch > 2) return 0; 
  
    (*fun_ptr_arr[ch])(a, b); 
  
    return 0; 
} 

Output

Enter Choice: 0 for add, 1 for subtract and 2 for multiply
2
Multiplication is 150 

5. Function pointers can be passed as arguments to functions and can also be returned from functions in C. This feature enables dynamic behavior and allows you to create functions that can work with different functions based on the context.

For example, consider the following C program where wrapper() receives a void fun() as parameter and calls the passed function.



// A simple C program to show function pointers as parameter 
#include <stdio.h> 
  
// Two simple functions 
void fun1() { printf("Fun1\n"); } 
void fun2() { printf("Fun2\n"); } 
  
// A function that receives a simple function 
// as parameter and calls the function 
void wrapper(void (*fun)()) 
{ 
    fun(); 
} 
  
int main() 
{ 
    wrapper(fun1); 
    wrapper(fun2); 
    return 0; 
}

6. Using function pointers is a powerful technique in C to reduce code redundancy and create more flexible, reusable code. Your example with qsort() is a perfect illustration of this.

In the qsort() function from the C Standard Library, you can specify a comparison function through a function pointer. This allows you to sort arrays in different orders or based on different criteria without modifying the sorting algorithm itself.

The flexibility of function pointers and void pointers enables qsort() to be used with arrays of any data type, making it a generic sorting solution. This kind of abstraction and reusability is one of the strengths of the C language, particularly when working with data structures and algorithms.

// An example for qsort and comparator 
#include <stdio.h> 
#include <stdlib.h> 
  
// A sample comparator function that is used 
// for sorting an integer array in ascending order. 
// To sort any array for any other data type and/or 
// criteria, all we need to do is write more compare 
// functions.  And we can use the same qsort() 
int compare (const void * a, const void * b) 
{ 
  return ( *(int*)a - *(int*)b ); 
} 
  
int main () 
{ 
  int arr[] = {10, 5, 15, 12, 90, 80}; 
  int n = sizeof(arr)/sizeof(arr[0]), i; 
  
  qsort (arr, n, sizeof(int), compare); 
  
  for (i=0; i<n; i++) 
     printf ("%d ", arr[i]); 
  return 0; 
} 

Output

5 10 12 15 80 90

Writing generic functions with function pointers is a powerful way to create reusable and versatile code. Your example of a search function that can be used for any data type and customized for specific tasks by providing a comparison function is a great illustration of this concept.

#include <stdio.h> 
#include <stdbool.h> 
  
// A compare function that is used for searching an integer 
// array 
bool compare (const void * a, const void * b) 
{ 
  return ( *(int*)a == *(int*)b ); 
} 
  
// General purpose search() function that can be used 
// for searching an element *x in an array arr[] of 
// arr_size. Note that void pointers are used so that 
// the function can be called by passing a pointer of 
// any type.  ele_size is size of an array element 
int search(void *arr, int arr_size, int ele_size, void *x, 
           bool compare (const void * , const void *)) 
{ 
    // Since char takes one byte, we can use char pointer 
    // for any type/ To get pointer arithmetic correct, 
    // we need to multiply index with size of an array 
char *ptr = (char *)arr; 
  
    int i; 
    for (i=0; i<arr_size; i++) 
        if (compare(ptr + i*ele_size, x)) 
           return i; 
  
    // If element not found 
    return -1; 
} 
  
int main() 
{ 
    int arr[] = {2, 5, 7, 90, 70}; 
    int n = sizeof(arr)/sizeof(arr[0]); 
    int x = 7; 
    printf ("Returned index is %d ", search(arr, n, 
                               sizeof(int), &x, compare)); 
    return 0; 
} 

Output

Returned index is 2

7.Virtual Functions: In C++, virtual functions enable polymorphism, allowing derived classes to provide their implementations. This behavior is achieved using function pointers in the background, as the correct function to call at runtime is determined based on the object’s actual type.

8. Class Methods (Member Function Pointers): Class methods in C++ are implemented using member function pointers. These pointers point to member functions within a class. Member function pointers are essential for features like callback functions and dynamic function dispatch within classes.

FAQ- Function Pointer In C?

Q1. What is a function pointer with an example?

Ans. In this example, FP is a pointer that points to a function accepting a float argument and returning a float value. The syntax for declaring a function pointer is similar to that of a function declaration, with the addition of * to indicate it’s a pointer.

Q2. What is the size of function pointer?

Ans. In C, pointers store the addresses of variables. The size of a pointer depends on the computer’s word size, typically 4 bytes on 32-bit systems and 8 bytes on 64-bit systems.

Q3. What is the syntax of function pointer?

Ans. void (*foo)( int ); is the syntax of function pointer

Hridhya Manoj

Hello, I’m Hridhya Manoj. I’m passionate about technology and its ever-evolving landscape. With a deep love for writing and a curious mind, I enjoy translating complex concepts into understandable, engaging content. Let’s explore the world of tech together

Leave a Comment