Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
Function pointers in C are a powerful feature that allows programmers to store the address of a function and call it indirectly through the pointer. This provides flexibility in designing modular and dynamic programs, enabling techniques like callback functions and runtime decision-making. In this article, we’ll explore the concept of function pointers, their syntax, applications, and examples to enhance your understanding of this advanced C programming concept.
The pointer that points towards a function is known as function pointers. It is also known as subroutine pointer or procedure pointer. It is an indirect method to invoke a function because it is called through a variable instead of an identifier, which is a more direct method.
Syntax of Function Pointer
return type(*pointer_name)(type_1, type_2,….);
For example:
float(*pt)(int, int);
In the above example, pt is a pointer that returns a float value and accepts two integer values.
Sample code of Function Pointer
Following is the sample code of adding two numbers using function pointer implemented in C++
C++
C++
#include<iostream> #include<conio.h> int add(int a, int b) { int sum = 0; sum = a + b; return sum; } int main() { int sum; int(*pt)(int, int) = add; sum = pt(621,361); std::cout<<"Sum is "<<sum; return 0; }
You can also try this code with Online C++ Compiler
Following is sample code of adding two numbers using function pointer implemented in C
C
C
#include<stdio.h> int add(int a, int b) { int sum = 0; sum = a + b; return sum; } int main() { int sum; int(*pt)(int, int) = add; sum = pt(220,210); printf("Sum is %d", sum); return 0; }
Like pointers, function pointers can also be stored in an array. It is useful when we do not know which function would be called in advance. For example, the following code will be implemented in C++ to create a basic calculator.
C++
C++
#include<iostream> #include<stdio.h> #include<conio.h> int add(int a, int b) { int sum = 0; sum = a + b; return sum; } int sub(int a, int b) { int diff = 0; diff = a - b; return diff; } int mul(int a, int b) { int mul = 0; mul = a * b; return mul; } int divid(int a, int b) { int ans = 0; ans = a / b; return ans; } int main() { int result,x,y; int(*pt[4])(int, int); pt[0] = add; pt[1] = sub; pt[2] = mul; pt[3] = divid; std::cout<<"Enter the values of x and y :"; std::cin>>x>>y; result=(*pt[0]) (x,y); // Calling add() function. std::cout<<"\nSum of two values is : "<<result; result =(*pt[1]) (x,y); // Calling sub() function. std::cout<<"\nDifference of two values is : "<<result; result = (*pt[2]) (x,y); // Calliung sub() function. std::cout<<"\nMultiplication of two values is : "<<result; result =(*pt[3]) (x,y); // Calling div() function. std::cout<<"\nDivision of two values is : "<<result; return 0; }
You can also try this code with Online C++ Compiler
In C, pointers can be passed to functions as arguments. This enables functions to modify the values of variables stored at the memory addresses pointed to by the pointers. This is particularly useful for passing large data structures or arrays efficiently.
Example
C
C
#include <stdio.h>
// Function to update the value using a pointer void updateValue(int *ptr) { *ptr = 100; // Modify the value at the address pointed to by ptr }
int main() { int num = 10; printf("Before: %d\n", num); // Output: 10
updateValue(&num); // Pass the address of num printf("After: %d\n", num); // Output: 100
Here, the updateValue function uses a pointer to directly modify the value of num in the main function.
Referencing and Dereferencing of Function Pointer in C
A function pointer stores the address of a function, allowing you to reference (assign a function to a pointer) and dereference (call the function through the pointer).
Here, the funcPtr references the displayMessage function, and the function is called indirectly through the pointer.
Program to Pass Pointers with Functions in C
Pointers can also be passed to functions to manipulate arrays, strings, or other data structures. This allows efficient data handling without duplicating the data.
Example: Passing an Array Using Pointers
C
C
#include <stdio.h>
// Function to print an array void printArray(int *arr, int size) { for (int i = 0; i < size; i++) { printf("%d ", *(arr + i)); } printf("\n"); }
int main() { int numbers[] = {1, 2, 3, 4, 5}; int size = sizeof(numbers) / sizeof(numbers[0]);
Here, the printArray function receives the pointer to the array numbers and iterates through the elements using pointer arithmetic.
Advantages of Function Pointers
Function pointers produce a method to pass around instructions on doing a task.
In C, the function pointer is a way to pass a function as an argument to another function.
Disadvantages of Function Pointers
While function pointers in C offer flexibility and power, they also come with certain disadvantages that developers should consider:
Increased Complexity: Understanding and managing function pointers can be challenging, especially for beginners, making the code harder to read and maintain.
Debugging Challenges: Errors related to incorrect function pointer usage, such as null pointer dereferencing or incorrect type casting, can be difficult to diagnose and debug.
Potential Security Risks: Function pointers, if mishandled, can introduce vulnerabilities like code injection or buffer overflow attacks, compromising the security of the program.
Loss of Type Safety: Improper casting of function pointers may lead to undefined behavior, as the compiler cannot always enforce strict type checking.
Performance Overhead: Indirect function calls through pointers are slightly slower than direct calls because they add an extra layer of indirection.
Reduced Portability: Overuse of function pointers can make the code less portable and harder to adapt to different platforms or architectures.
Function pointers are used when you want to create a callback mechanism and need to pass the address of one function to another function.
Can a function pointer be null?
In C, a function pointer can be null.
Can we increment function pointer?
We cannot increment or decrement function pointer, but an array of function pointers can be increment.
What is the meaning of the expression: int(*ptr[3])()?
The expression represents an array of function pointers.
Conclusion
In this article, we have discussed Function Pointers in C. They are a powerful feature that provides flexibility, allowing functions to be passed as arguments, called dynamically, and referenced indirectly. While they offer numerous advantages, such as enabling callback functions and enhancing modularity, they also introduce complexities, debugging challenges, and potential security risks.