Ad Code

Responsive Advertisement

Function Pointer in C ? With example

 

C Function Pointer


As we know that we can create a pointer of any data type such as int, char, float, we can also create a pointer pointing to a function. The code of a function always resides in memory, which means that the function has some address. We can get the address of memory by using the function pointer.

Let's see a simple example.

c
#include <stdio.h> // Function declarations int add(int a, int b); int subtract(int a, int b); int main() { // Define a function pointer that can point to functions taking two integers and returning an integer int (*operation)(int, int); // Initialize the function pointer to point to the 'add' function operation = add; // Perform addition int result = operation(5, 3); printf("Result of addition: %d\n", result); // Change the function pointer to point to the 'subtract' function operation = subtract; // Perform subtraction result = operation(5, 3); printf("Result of subtraction: %d\n", result); return 0; } // Function definitions int add(int a, int b) { return a + b; } int subtract(int a, int b) { return a - b; }


 Output:

rust
Result of addition: 8 Result of subtraction: 2


In this example:

 1. We declare two functions, add and subtract, each taking two integers and returning an integer.

2.  We define a function pointer named operation that can point to functions with the same signature as add and subtract.

3.  We initialize operation to point to the add function, and then we use it to perform addition and print the result.

This demonstrates the flexibility of function pointers in C, allowing you to switch between different functions at runtime based on your needs.


Declaration of a function pointer



Till now, we have seen that the functions have addresses, so we can create pointers that can contain these addresses, and hence can point them.


Syntax of function pointer


c
returnType (*functionPointerName)(parameterType1, parameterType2, ...);


Here's an example of declaring a few different types of function pointers:

c
#include <stdio.h> int add(int a, int b); void printMessage(const char *message); double calculateAverage(double arr[], int size); int main() { // Declaration of function pointers int (*addPtr)(int, int); // Function pointer for int-returning function void (*printMessagePtr)(const char *); // Function pointer for void-returning function double (*averagePtr)(double[], int); // Function pointer for double-returning function return 0; }


In the example above:

1.  addPtr is a function pointer that can point to a function returning an int and taking two int parameters.

2.  printMessagePtr is a function pointer that can point to a function returning void (i.e., no return value) and taking a pointer to a constant character string as its parameter.

3.  averagePtr is a function pointer that can point to a function returning a double and taking an array of double and an int as its parameters.


Calling a function through a function pointer



We already know how to call a function in the usual way. Now, we will see how to call a function using a function pointer.


1. Declare the function pointer: 

First, declare the function pointer with the appropriate return type and parameter types that match the function you intend to call. This declaration is usually done at the beginning of your code.

2. Assign the function pointer: 

Assign the function pointer to the address of the function you want to call.

3. Call the function through the function pointer: 

Invoke the function using the function pointer as if it were an actual function.


Here's an example of calling a function through a function pointer:

c
#include <stdio.h> int add(int a, int b) { return a + b; } int subtract(int a, int b) { return a - b; } int main() { // Declare a function pointer for a function that takes two integers and returns an integer int (*operation)(int, int); // Assign the function pointer to the 'add' function operation = add; // Call the function through the function pointer int result = operation(5, 3); printf("Result of addition: %d\n", result); // Change the function pointer to point to the 'subtract' function operation = subtract; // Call the function through the function pointer result = operation(5, 3); printf("Result of subtraction: %d\n", result); return 0; }


In this example:

1. We have two functions, add and subtract, each with the same signature (taking two integers and returning an integer).

2. We declare a function pointer named operation that has the same signature as the functions it can point to.

3. We assign the operation function pointer to the address of the add function and use it to call add. Then, we change the pointer to point to the subtract function and use it to call subtract.


Let's understand the function pointer through an example.

c
#include <stdio.h> // Function declarations int add(int a, int b); int subtract(int a, int b); int main() { // Declare a function pointer that can point to functions taking two integers and returning an integer int (*operation)(int, int); // User's choice: 1 for addition, 2 for subtraction int choice; printf("Choose an operation:\n"); printf("1. Addition\n"); printf("2. Subtraction\n"); scanf("%d", &choice); // Initialize the function pointer based on the user's choice if (choice == 1) { operation = add; } else if (choice == 2) { operation = subtract; } else { printf("Invalid choice.\n"); return 1; // Exit with an error code } int a, b; printf("Enter two integers: "); scanf("%d %d", &a, &b); // Call the chosen operation through the function pointer int result = operation(a, b); if (choice == 1) { printf("Result of addition: %d\n", result); } else if (choice == 2) { printf("Result of subtraction: %d\n", result); } return 0; } // Function definitions int add(int a, int b) { return a + b; } int subtract(int a, int b) { return a - b; }

 Output:

yaml
Choose an operation: 1. Addition 2. Subtraction 1 Enter two integers: 5 3 Result of addition: 8


In this example:

1. We declare a function pointer named operation that can point to functions with the same signature as the add and subtract functions.

2. The user is prompted to choose an operation (addition or subtraction), and their choice determines which function the operation pointer will point to.

3. The user is then asked to input two integers, and the chosen operation is performed through the function pointer, with the result printed based on the user's choice.

4. This demonstrates how function pointers can be used to select and call different functions at runtime based on user input.



Array of Function Pointers?


Function pointers are used in those applications where we do not know in advance which function will be called. In an array of function pointers, array takes the addresses of different functions, and the appropriate function will be called based on the index number.

Let's understand through an example.


c
#include <stdio.h> // Function declarations for operations int add(int a, int b); int subtract(int a, int b); int multiply(int a, int b); int divide(int a, int b); int main() { // Define an array of function pointers for different operations int (*operations[])(int, int) = {add, subtract, multiply, divide}; int choice, num1, num2; printf("Simple Calculator\n"); printf("1. Addition\n"); printf("2. Subtraction\n"); printf("3. Multiplication\n"); printf("4. Division\n"); printf("Choose an operation (1-4): "); scanf("%d", &choice); // Validate the user's choice if (choice < 1 || choice > 4) { printf("Invalid choice.\n"); return 1; } printf("Enter two numbers: "); scanf("%d %d", &num1, &num2); // Calculate the array index based on the user's choice int operationIndex = choice - 1; // Call the selected operation using the array of function pointers int result = operations[operationIndex](num1, num2); printf("Result: %d\n", result); return 0; } // Function definitions for the calculator operations int add(int a, int b) { return a + b; } int subtract(int a, int b) { return a - b; } int multiply(int a, int b) { return a * b; } int divide(int a, int b) { if (b == 0) { printf("Division by zero is not allowed.\n"); return 0; // Return 0 as a special value } return a / b; }

Expected Output:

markdown
Simple Calculator 1. Addition 2. Subtraction 3. Multiplication 4. Division Choose an operation (1-4): 2 Enter two numbers: 8 3 Result: 5

In this example:

1. We define an array of function pointers, operations[], which can point to functions with the same signature as the calculator operations.

2. The user selects an operation, and we calculate the array index to choose the appropriate function pointer from the array.

3. The selected operation is then called using the function pointer from the array, and the result is printed.

This demonstrates how an array of function pointers can be used to implement different functions based on user input in a more compact and dynamic manner.

Post a Comment

0 Comments